QA Interview Hub · Knowledge base · Quizzes · Українська

System Design

Scaling and reliability

Vertical and horizontal scaling

Vertical scaling is a bigger machine, horizontal scaling is more instances behind a load balancer. The first has a ceiling and stays a single point of failure; the second requires a stateless service, otherwise state in the memory of one instance breaks requests on another. Scaling is verified with load, stress, spike and soak tests on a realistic data volume, judged by p95, p99 and error rate.

System design · Scaling

On staging there are two instances and login suddenly "forgets" the user. Why?

A service worked flawlessly on one machine. It was deployed as two instances behind a load balancer and some users started falling out of their session: a request lands on an instance that knows nothing about them. Scaling changes not only speed but the class of possible bugs itself. The lesson covers two ways to add capacity, what they demand from a service, and how QA verifies that the system really scales.

How it works and why

Vertical scaling: a bigger machine (CPU, memory). No code changes, but there is a ceiling, the price grows faster than the capacity and the machine stays a single point of failure. Horizontal: more instances behind a load balancer. There is almost no ceiling and one instance failing does not take the service down, but the service must be stateless: everything needed to answer is in the request or in shared storage (database, cache, session store), not in process memory. Otherwise two instances see different "states of the world".

Two ways to grow

Vertical

A bigger machine

Simple, no code changes. A ceiling and a single point of failure.

Horizontal

More instances

Almost no ceiling, more resilient. Needs stateless, shared state, a balancer.

Figure 1. Both are legitimate; the choice depends on load and code.

Autoscaling adds or removes instances based on a metric: CPU, request count, queue length. Nuances tests catch: a new instance does not start instantly (warm-up, health check), and a database almost always scales worse than services, so the bottleneck simply moves there.

Example: flaky login on two instances

One instance:  POST /login -> 200, GET /me -> 200
Two instances:  POST /login -> 200 (A), GET /me -> 401 (B)

The session is stored in the memory of instance A and the balancer sent the next request to B. On one machine this does not reproduce. Diagnosis: repeat the same sequence several times and check which instance answered (a header or a log). The right fix is to move sessions to shared storage or switch to tokens the server can verify on its own. The temptation to "enable sticky sessions" hides the problem: when an instance dies the user is logged out anyway.

What QA tests

  • Load test: the expected load, p95 and p99 latency, error rate.
  • Stress test: where and how the system breaks: degrades gradually or falls over completely.
  • Spike test: a sudden peak (a sale, a payout at 9:00): does autoscaling keep up.
  • Soak test: hours of load: memory and connection leaks.
// k6
export const options = {
  scenarios: {
    peak: {
      executor: 'ramping-arrival-rate',
      startRate: 10, timeUnit: '1s',
      preAllocatedVUs: 100, maxVUs: 400,
      stages: [{ target: 200, duration: '2m' }, { target: 200, duration: '5m' }],
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<500', 'p(99)<1200'], // ms
    http_req_failed: ['rate<0.01'],
  },
};

Thresholds turn the test into an automatic check: if p95 goes above 500 ms the run fails. The arrival rate model keeps the set flow of requests even when the system slows down (as long as there are VUs: maxVUs, without it the ceiling is preAllocatedVUs), and is therefore more honest than a fixed number of virtual users.

Limits and common mistakes

  • Load on staging with an empty database: a query fast on 1000 rows is slow on 50 million. You need a realistic data volume and profile.
  • The load generator becomes the bottleneck itself: a weak machine running k6 measures itself, not the service.
  • Looking at the average: it hides the tail. Look at p95 and p99.
  • Testing only services and forgetting the database, where scaling is harder.

Check yourself

After moving to two instances random 401s appeared. What is the hypothesis and how to check it?

Answer

Session state lives in the memory of one instance. Repeat login and requests several times and watch which instance answered: the 401 comes from a different one than issued the session.

Why does a load test on an empty database give false confidence?

Answer

Query time depends on data volume and indexes. On small data even a full scan is fast, and in production it becomes the bottleneck.

In an interview. Junior: Vertical scaling is simpler but has a ceiling. Horizontal gives resilience but requires stateless services. Middle/Senior: I verify scaling with load, stress, spike and soak tests on a realistic data volume, look at p95, p99 and error rate, and put thresholds into the test itself. Separately I hunt for bugs that appear only with several instances: in-memory state, local caches, sticky sessions, and watch whether the database became the bottleneck.

Idempotency, retries and rate limiting

Idempotency means a repeated call has the same effect on server state as the first one; by RFC 9110 GET, PUT and DELETE are idempotent and POST is not. For payments a POST is made safe by an idempotency key: the server stores the result under the key and returns it on a repeat. Retries with backoff and jitter apply to idempotent operations or keyed requests, while rate limiting answers 429.

System design · Scaling

The client sent a transfer, the response got lost, and it retried. How many times was the money debited?

The network is unreliable. The client sent a POST for a transfer, the server executed it, but the response never arrived. The client does not know what happened and repeats the request. Without protection the money is debited twice. Three mechanisms work together: idempotency makes a repeat safe, retries with backoff make it sensible, rate limiting protects the server from repeats that are too frequent.

How it works and why

Idempotency: a repeated call has the same effect on the server state as the first one. By the HTTP specification (RFC 9110) GET, PUT and DELETE are idempotent and POST is not. For payments POST is made idempotent with an idempotency key: the client generates a unique key and passes it in a header (the common name is Idempotency-Key). The server stores the result by key and on a repeat returns the same result without creating a new payment.

POST /transfers
Idempotency-Key: 7c1f2b9e-5d44-4b6a-9f10-3a0d1e2c8b77
Content-Type: application/json

{"from":"acc-1","to":"acc-2","amount":100}

The server ties the key to the request and its result. The same key with the same body: the stored response is returned. The same key with a different body: a client error, not a reason to silently perform a different payment. Hence the set of tests.

Example: a race of two identical requests

The trickiest case: the repeat arrives while the first request is still running. If the check "was this key seen?" and the storing of the result are not atomic, both pass the check and both execute.

const key = crypto.randomUUID();
const send = () =>
  request.post('/transfers', {
    data: { from: 'acc-1', to: 'acc-2', amount: 100 },
    headers: { 'Idempotency-Key': key },
  });

const [a, b] = await Promise.all([send(), send()]);
const ids = new Set([(await a.json()).id, (await b.json()).id]);

expect(ids.size).toBe(1); // one transfer
expect(await balance('acc-1')).toBe(900); // from 1000: one debit

Assumption: the starting balance is 1000. Another acceptable outcome: the second request gets 409 because the first is still running. Then check that there is one debit and that after completion a repeat returns the same transfer. The product-side fix: a unique index on the key or a lock, not a "read first" check in code.

Test cases for the key

  • A repeat with the same key and body: the same transfer, one debit.
  • The same key with a different body: an error, not silent ignoring.
  • Two parallel requests with one key: one transfer.
  • A repeat after the key retention period: behaviour per the service specification.

Retries with backoff and jitter

The client repeats the request with a growing pause (1, 2, 4 seconds) and a random offset so thousands of clients do not retry at the same moment and finish off a server that just recovered. Only idempotent operations, or operations with an idempotency key, may be retried. The number of attempts and the total time should be limited too.

Rate limiting

It limits a client's requests per time, for example 100 per minute. Exceeding it gives 429 Too Many Requests, often with a Retry-After header. Algorithms: token bucket, sliding window. Tests cover the limit boundary (the 100th passes, the 101st does not), window reset, independence of limits of different clients and that on 429 the client waits instead of retrying at once.

Limits and alternatives

An idempotency key only protects against a repeat of the same request: two different requests for the same amount with different keys are both executed. Keys are kept for a limited time, so a repeat after the retention period runs the operation again. A rate-limit counter in one instance's memory does not see requests to the others: behind a load balancer it is kept in a shared store such as Redis.

Common mistakes

  • Retrying POST without a key: each "safe" attempt can create a duplicate.
  • Backoff without jitter: all clients come back at once in waves.
  • Testing the limit with one client and not checking that limits are independent per key or user.

Check yourself

The same key arrived with a different body. What should the server do and why?

Answer

Reject with an error (often 422 or 409): it is either a client bug or a key collision. Quietly returning the old response means the client thinks a different payment was done.

Why are retries without jitter dangerous even with backoff?

Answer

Clients that failed at the same time retry at the same moments and create synchronised waves of load. A random offset spreads them out.

In an interview. Junior: An idempotent operation gives the same result on a repeat. For payments an idempotency key is used so a repeat does not debit twice. Middle/Senior: I test a repeat, the same key with a different body and parallel requests with one key because a race is what breaks a naive implementation. The client retries with exponential backoff and jitter only idempotent operations (GET, PUT, DELETE) or POST with a key, and I check rate limiting at the limit boundary and the client's reaction to 429 and Retry-After.

CAP and reliability at a basic level

The CAP theorem says that during a network partition a distributed system must choose between consistency and availability. The choice is made per feature: for a balance an error is better than a stale number, while a catalogue may serve slightly stale data. QA tests the chosen behaviour through fault injection, together with timeouts, a circuit breaker with recovery and degradation of non-critical features.

System design · Scaling

Ledger is unavailable. Show the last known balance or show an error?

Ledger is down for a minute. The app has two options: show a balance from a cache that is 10 minutes old, or honestly say "unavailable right now". For a news feed the first is fine. For a balance by which the user decides whether funds are enough, it is not. That is exactly the choice CAP describes. The lesson covers this choice at the level needed in an interview and the patterns that keep one service's failure from taking down the rest.

How it works and why

The CAP theorem: during a network partition (P) a distributed system must choose between consistency (C: everyone reads the latest data) and availability (A: every request gets a response). Partitions do happen in real networks, so the choice is effectively between C and A at the moment of failure. When the network is healthy you can have both, but latency and the cost of agreement force trade-offs again.

What is chosen during a failure

CP

Better an error

Balance, debits. Refuse rather than act on stale data and go negative.

AP

Better stale

Catalogue, likes, recommendations. Answer even if the data is a little old.

Figure 1. CP and AP: both choices are legitimate, depending on the feature.

The practical conclusion for QA: you need to know which behaviour was chosen for each feature and test exactly that. If the balance is meant to be CP, then when Ledger is unavailable the API returns an error, not an old balance from a cache.

Example: a dependency failure

test('balance: an error, not a stale number', async ({ page }) => {
  await page.goto('/account');
  await expect(page.getByTestId('balance')).toHaveText('1 500,00');

  await page.route('**/api/ledger/balance', (r) => r.abort());
  await page.reload();

  await expect(page.getByRole('alert')).toContainText('Balance is temporarily unavailable');
  await expect(page.getByTestId('balance')).toBeHidden();
});

The test reproduces the failure at the network level and checks not only that a message is present but that the stale number is gone. If the number remains, the system chose AP where CP was expected. The fix belongs to the product (do not cache the balance or do not show the cache without a label), not to the test.

Reliability patterns

  • Timeout: on every call to another service. Without it one slow service blocks all threads.
  • Circuit breaker: after a series of errors it opens: the dependency is not called for a while and a fallback or error is returned at once; then a trial request (half-open) decides whether to close again.
  • Graceful degradation: if recommendations are unavailable, the payment page still works.
  • Bulkhead: resource isolation so one feature's failure does not take all connections.

This is verified with chaos testing and fault injection: delay a dependency's responses, kill an instance, cut the database connection and see whether the system behaves as designed. Start on staging with controlled experiments and a clear criterion of what counts as normal.

Limits and mistakes

  • CAP is not about slowness: "the system is slow" is not the same as a network partition. It is a simplified model; do not stretch it further in an interview.
  • One choice for the whole system. In reality the choice is per feature: balance CP, catalogue AP.
  • Retries without a circuit breaker during a failure increase load on an already sick dependency.

Check yourself

A test disabled Ledger and the UI showed an old balance without a label. A bug or normal?

Answer

It depends on the choice for the feature. If the balance is meant to be CP, it is a bug: the client may act on an outdated number. If AP is acceptable, the cache is shown with a staleness label.

What does a circuit breaker do and what to check in a test?

Answer

After a series of errors it stops calling the dependency and returns a fallback or error at once. Check that requests really stop, that the response is fast and that calls resume after the dependency recovers.

In an interview. Junior: CAP says that during a network failure you must choose between consistency and availability: for a balance an error is better, for a catalogue slightly stale data is acceptable. Middle/Senior: The choice is made per feature, and I test exactly that through fault injection: delays, dependency failures, dropped connections. I check timeouts, a circuit breaker with recovery, degradation of non-critical features and that CP features do not return stale data.