A load balancer spreads requests across several identical instances of a service and stops sending traffic to unhealthy ones through health checks. Services behind it must be stateless: state lives in a shared store, not in process memory, otherwise a request that lands on another instance returns, for example, 404. QA separately tests an instance failing, mixed versions during a rolling deploy and load balancer timeouts.
System design · Backend
The first request created a payment draft, the second got a 404. What changed between them?
A test creates a payment draft and immediately reads it by id. Locally everything works, but on a staging with three instances of the service about two reads out of three return 404. The code changed nothing between the two calls. The instance that handled them changed: the draft sat in the memory of the first one, and the read landed on the second. This is a typical bug when QA moves from a single process to a system behind a load balancer. The lesson covers how this scheme is built and what to test in it.
How it works and why. One instance of a service has a throughput limit and is a single point of failure. So several identical instances are run and a load balancer (LB) is put in front of them to distribute requests. An LB works at L4 (by TCP connections) or L7 (understands HTTP, can route by path or header). The algorithms differ: round robin in turn, least connections to the least loaded, a hash of IP or key so one client lands on the same instance. Besides distribution an LB runs health checks: it periodically probes an instance and stops sending traffic to it if it is unhealthy.
The path of a request through the load balancer
Figure 1. Any instance must answer any request: that is why the state lives in shared stores.
Stateless versus sticky. A stateless service keeps no client state in process memory: the session is in a token or a shared store. Then any instance handles any request and the service scales easily. Sticky sessions bind a client to one instance. This is simpler for stateful logic, but when the instance dies the session is lost and the load is distributed unevenly.
Example: checking that the state is not in memory. The faulty code keeps drafts in process memory:
// before: works with one instance, breaks behind an LBconst drafts = newMap<string, Draft>();
app.post('/drafts', (req, res) => {
const id = randomUUID();
drafts.set(id, req.body);
res.status(201).json({ id });
});
The test must make requests land on different instances. It helps if the service returns a service header with an instance identifier (here a hypothetical x-served-by; whether one exists depends on the project):
test('a draft is readable from any instance', async ({ request }) => {
const created = await request.post('/api/drafts', { data: { amount: 30 } });
const { id } = await created.json();
const instances = newSet<string>();
for (let i = 0; i < 20; i++) {
const res = await request.get('/api/drafts/' + id);
expect(res.status()).toBe(200);
instances.add(res.headers()['x-served-by'] ?? 'unknown');
}
// proves that the requests really went to different instancesexpect(instances.size).toBeGreaterThan(1);
});
The fix is a shared store: the draft lives in the database or Redis and any instance finds it. The last line of the test matters: without it a green result may mean that all twenty requests went to the same instance.
State in memory versus a shared store
Wrong
A Map in the process
The draft exists only on instance 1. A request to instance 2 gives 404, and when instance 1 dies the data is gone.
Right
A shared store
The draft is in the DB or Redis. Any instance sees it, and an instance can be replaced without losing data.
Figure 2. The in-memory state bug appears only with two or more instances.
What else to test.
An instance dying mid-flow. The user is in the middle of a scenario: can they continue on another instance without logging in again.
Rolling deploy. During an update some instances run the new version and some the old, and requests mix. The new version must read data written by the old one and vice versa, so database schema changes are made in two steps (expand first, contract later).
LB timeouts. A long request (a report, an export) may be cut at the LB before the service answers: many balancers have an idle timeout, for example 60 seconds by default in AWS ALB. Check the value on the project.
Health check. Does the LB take out an instance that responds badly, and put it back once it recovers.
Limits and alternatives. A Playwright or other HTTP client may keep one connection open, and an L4 balancer will send all requests to the same place: to hit different instances, new connections are made. Sticky sessions are sometimes justified, for example for WebSocket, but then instance failure is handled explicitly. For several regions another layer is added: DNS or a global balancer between regions, and the failure of a whole region has to be tested too.
Common mistakes.
Testing on only one instance: state bugs do not show.
Not checking that the requests were really distributed: a green test proves nothing.
Forgetting mixed versions during a rolling deploy.
Ignoring LB timeouts for long operations: on a stand without an LB everything works.
Check yourself
A test creates a draft and reads it: green on one instance, sometimes 404 behind an LB with three. What does it mean and where to look for the bug?
Answer
The draft state lives in the memory of an instance and not in a shared store. A request to another instance does not see it. Look for code that keeps data in a process variable (a Map, a local cache) and move it to the DB or Redis.
Why must the new version of a service work with the old data schema during a rolling deploy?
Answer
During the update both versions run at the same time and share one DB. If the new version requires a new column the old ones do not fill, or a migration drops a field the old ones still read, part of the requests will start failing. So changes are made in two steps: first add the compatible part, and remove the old only after the update is complete.
Related lessons: "Vertical and horizontal scaling", "Cache: where it stands and what breaks in it", "The database: indexes, replication, sharding".
In the interview.Junior: A load balancer distributes requests among instances and removes unhealthy ones. The services behind it should be stateless. Middle/Senior: I test separately an instance dying mid-scenario, in-memory state (sequential requests to different instances with a check that they really diverged), mixed versions during a rolling deploy and LB timeouts for long operations. I treat sticky sessions as a compromise, not the norm.
Cache: where it stands and what breaks in it
A cache keeps frequently read data in a fast store, but the copy can drift from the source. Almost all cache problems come down to how long the copy may be stale. For each type of data the promised delay must be known and checked with a wait that has an upper bound, not a fixed pause. Cache keys are tested with two users, plus an unavailable cache and a stampede.
System design · Backend
After a transfer the app shows the old balance while the database already has the new one. Where did the state get stuck?
A user made a transfer and refreshed the page: the balance did not change. Half a minute later it did. A test reads the balance from the API right after the transfer and fails only sometimes. The database is right, there is no error in the logs. The culprit is a cache: the balance was read from a store that does not know about the change yet. A cache is fast and useful, but it hides the most insidious bugs. The lesson covers where a cache sits, which patterns are used and what breaks in it.
How it works and why. A cache keeps frequently read data in a fast store (for example Redis in memory) to avoid going to the DB each time. The speed gap between memory and disk is large and most reads repeat. The price: a copy of the data may diverge from the source. Almost all cache problems are forms of one question: how long may the copy be stale and who controls it.
Cache-aside: read and write
Figure 1. The third step is the subtlest: skipping it or doing it in the wrong order gives stale data.
Patterns.
Cache-aside: the service looks in the cache and, if it is missing, reads from the DB and stores it. The most common.
Write-through: a write goes to the cache and the DB together, so the cache is always fresh, but writes are slower.
TTL: an entry lives in the cache for a limited time and disappears. It is insurance against forever stale data.
The hardest part is invalidation. For a product catalogue, 30 seconds of a stale price is often acceptable. For an account balance it is not. So for each data type you need to know which delay is promised and test exactly that.
Example: stale data and somebody else's data. The first check: after a change the new value must appear within the promised time. Instead of a fixed pause we use expect.poll and verify the upper bound:
The second check is about security. A wrong cache key (without the user id or currency) gives one user another user's data. That is a security incident, not a cosmetic issue:
test('the balance is not shared between users', async ({ browser }) => {
const a = awaituserContext(browser, 'alice');
const b = awaituserContext(browser, 'bob');
const balA = await (await a.get('/api/balance')).json();
const balB = await (await b.get('/api/balance')).json();
expect(balB.accountId).not.toBe(balA.accountId);
});
(userContext here is a project helper that returns a user's API context.) The order is what matters in the test: the first user warms the cache, the second reads the same keys.
The cache key
Wrong
balance
One key for everyone. After the first read every user sees the balance of whoever warmed the cache.
Right
balance:user:42:EUR
The key contains everything the response depends on: the user and the currency. Private data is also marked private for HTTP caches.
Figure 2. The cache key must include everything that changes the response.
What else can break.
Cache stampede. A popular key expired and thousands of requests go to the DB at once. Cured by letting one request refresh while others wait, TTL spread (jitter) or background refresh. Checked by a load test.
Cache unavailable. The service must run slower but run, not return 500. Checked by turning the cache off in the test environment.
Negative answers. If "not found" is cached, a freshly created record will be unavailable for a while. This is easy to check with a "create and read at once" test.
Limits and alternatives. For tests a cache adds one more problem: the test reads data that a previous test or run put into the cache. In test environments it helps to have a way to flush the cache (an admin endpoint or a separate key prefix per run) or short TTLs. Not every read is worth caching: data that changes on every request only adds complexity. For money data some choose not to cache at all and read from the primary DB, keeping the cache for reference data.
Common mistakes.
Checking an update with a fixed pause instead of waiting for a condition with an upper bound.
Not checking the cache key with two different users.
Not flushing the cache between runs: the result depends on what the previous run left.
Assuming a cache is only an optimisation: it changes behaviour and its failure must be tested too.
Check yourself
The catalogue promises "the price updates within 30 seconds" and a test with waitForTimeout(5000) after a price change fails. What is wrong with the test?
Answer
The test checks the wrong bound: a 5-second pause is shorter than the promised 30 and the failure is not a bug. The right thing is to wait for a condition with an upper bound, TTL plus margin (expect.poll with a timeout of about 35 seconds). It would be a bug if the new value did not appear even after that time.
User Bob sees Alice's balance after Alice opened the page. What is the most likely cause and why is it critical?
Answer
The cache key does not contain the user identifier: the first request filled the shared key and the second read it. This is a leak of someone else's data, a security incident. The fix: include in the key everything the response depends on and add a test with two users where the first warms the cache.
Related lessons: "Client-server and the load balancer", "The database: indexes, replication, sharding", "Eventual consistency and sagas in tests".
In the interview.Junior: A cache speeds up reads but the data may be stale. So I check that after a change the new value appears and that the cache does not give out someone else's data. Middle/Senior: First I ask what delay is acceptable for each data type and check exactly that with expect.poll and an upper bound. Separately I test cache keys with two users, behaviour when the cache is unavailable, a stampede under load and cache flushing between runs. I do not cache balances and similar data without a clear invalidation strategy.
The database: indexes, replication, sharding
Indexes, replication and sharding address the limits of a single database, but each brings a new problem. An index slows writes, replication adds replication lag, and sharding complicates operations across shards. QA checks concurrent debits from one account with a parallel test, and wants the protection in the database itself: a conditional update or row locking, unique indexes and CHECK.
System design · Backend
Two parallel transfers of 60 each from an account holding 100. How much is left?
The account holds 100. Two requests at once ask to transfer 60 each. Each reads a balance of 100, sees that it is enough and debits. The result: a balance of minus 20, although each request behaved correctly on its own. Such an error does not show in sequential tests and comes alive only under concurrency. The database is where this and other traps live. The lesson covers indexes, replication, sharding and transactions from a QA viewpoint.
How it works and why. A single DB on a single server has limits: in data volume, reads, writes. So three techniques appear, each solving one problem and creating another. An index speeds up search at the price of slower writes. Replication raises read throughput at the price of lag. Sharding spreads data across servers at the price of complex cross-shard operations. It is exactly these new problems that need testing.
What each technique solves and what it creates
Figure 1. Each technique gives the tester its own class of checks.
Indexes. An index is a structure that lets you find rows quickly without scanning the whole table. For QA they matter in two places. First: slow queries on large volumes. On a stand with a thousand rows everything is fast, in production with 50 million it is not, so the query plan is inspected with EXPLAIN. Second: unique indexes as protection against duplicates:
CREATEUNIQUEINDEX ux_transfers_idem
ON transfers (client_id, idempotency_key);
Such an index guarantees at the database level that the same transfer request is not stored twice, even when two requests arrive at once. An application-level check "is there such a record already" does not guarantee this, because there is a window between the check and the insert.
Transactions and races: an example. The test from the start of the lesson runs parallel requests and checks an invariant: the balance is never negative.
test('parallel transfers never overdraw the account', async ({ request }) => {
// acc_1 holds 100, every transfer is 60const results = awaitPromise.all(
[1, 2, 3, 4, 5].map(() =>
request.post('/api/transfers', {
headers: { 'Idempotency-Key': crypto.randomUUID() },
data: { from: 'acc_1', to: 'acc_2', amount: 60 },
}),
),
);
const ok = results.filter((r) => r.status() === 201).length;
expect(ok).toBe(1);
const acc = await (await request.get('/api/accounts/acc_1')).json();
expect(acc.balance).toBe(40);
});
If the code reads the balance, checks and writes in separate steps, the test catches two or more successes and a negative balance. The fix at the database level: a conditional update in one statement, or a row lock, or an integrity constraint as the last line:
-- atomic: the check and the write in one statementUPDATE accounts
SET balance = balance - 60WHERE id = 'acc_1'AND balance >= 60;
-- 0 rows updated means insufficient funds-- last line of defenceALTERTABLE accounts ADD CONSTRAINT balance_non_negative CHECK (balance >= 0);
Replication. The primary takes writes, replicas serve reads. Replication is usually asynchronous, so there is replication lag: what was just written may not be on the replica yet. A typical bug: a user created a transfer, the history page reads from a replica and the transfer is not there. Testers check a read right after a write and behaviour under artificially increased lag. The typical fix: a read after one's own write goes to the primary.
Sharding. Data is spread across several DBs by a key, for example user_id. The difficulties: queries spanning several shards, transactions across shards (a transfer between users on different shards), rebalancing. For testing it matters to have data on different shards and not only on one, otherwise the most interesting cases stay invisible.
Two ways to debit funds
Wrong
Read, check, write
There is a window between read and write. Two requests read 100 and both debit 60.
Right
Conditional update
The check and the debit in one statement with a row lock. The second request sees 40 and is refused.
Figure 2. Only a parallel test catches such a bug: sequential ones pass.
Limits and alternatives. The default transaction isolation level in PostgreSQL is READ COMMITTED: it does not protect against the described race if the logic is split into several statements. Options: an atomic update (the simplest), SELECT ... FOR UPDATE to lock a row, a higher isolation level with retrying transactions on conflict. The choice depends on the DBMS and the load, so QA checks the behaviour with a parallel test instead of guessing. A parallel test does not prove the absence of a race, it only raises the chance of finding one; for critical places it is repeated many times.
Common mistakes.
Testing a transfer only sequentially: the race stays invisible.
Checking duplicates only at the application level, without a unique index in the DB.
Reading from a replica right after a write and being surprised by missing data.
Having test data on only one shard.
Drawing conclusions about speed on the small stand DB.
Check yourself
A test with five parallel transfers of 60 from an account holding 100 got two 201 successes and a balance of -20. What is the cause and the fix at the DB level?
Answer
A race: the code reads the balance, checks and writes in separate steps, so two requests read 100. The fix: an atomic UPDATE ... SET balance = balance - 60 WHERE id = ... AND balance >= 60 (check the updated row count), or SELECT ... FOR UPDATE, with CHECK (balance >= 0) as the last line of defence.
A user created a transfer and the history page does not show it at once but shows it a second later. What is the hypothesis and how to check it?
Answer
Replication lag: the list is read from a replica that has not yet received the write. We check which DB this endpoint reads from and run a "create and read at once" test (preferably with artificially increased replication lag). The fix: read-after-own-write from the primary or an explicit promise of the delay.
Related lessons: "Cache: where it stands and what breaks in it", "Message queues and delivery guarantees", "CAP and reliability at a basic level".
In the interview.Junior: Indexes speed up reads and can guarantee uniqueness. Replication scales reads but creates replication lag, and sharding spreads data by a key. Middle/Senior: I test read-after-write, transfers across shards and concurrent debits from one account with a parallel test that checks invariants (the balance is not negative, no duplicates). I want the protection in the DB: a conditional update or locking, unique indexes, CHECK, and not only a check in code.
Message queues and delivery guarantees
Most queues guarantee at-least-once delivery: a message is not lost but can arrive twice, because without an acknowledgement (ack) it is redelivered. So the consumer must be idempotent: the id of the processed message and the data change are written in one transaction. Tests cover a duplicate, a consumer crash between processing and ack, ordering (in Kafka only within a partition), the DLQ and consumer lag.
System design · Backend
The message "credit 30" arrived twice. How much money did the user get?
The transfer service puts a message "credit 30 to acc_2" on a queue. The consumer processed it but crashed before acknowledging it. The queue, receiving no acknowledgement, delivered the same message again. The balance rose by 60. A double processing appeared in a system without code errors. This is not a failure but normal behaviour of most queues. The lesson covers what a queue guarantees, why a consumer must be idempotent and what to test.
How it works and why. A queue (Kafka, RabbitMQ, SQS) decouples services in time: a producer puts a message and moves on, a consumer processes it when it can. This gives resilience to peaks and independence of services, but the system becomes asynchronous. To avoid losing a message the queue waits for an acknowledgement (ack) from the consumer and delivers again if it is missing. This is where delivery guarantees come from.
At-most-once: a message may be lost but is not duplicated. The acknowledgement is sent before processing.
At-least-once: a message is not lost but may arrive twice. The acknowledgement comes after processing. The most common option.
Exactly-once: achievable within one broker (for example Kafka transactions, deduplication in SQS FIFO queues within a time window), but at the boundary with external stores like your DB it is practically built from at-least-once and an idempotent consumer.
Why a duplicate appears
Figure 1. A crash between processing and acknowledgement is the source of duplicates: it cannot be avoided, only survived.
An idempotent consumer. At-least-once implies the main rule: processing the same message again must not change the result. Usually the consumer records the ids of processed messages and skips duplicates. It is important that the id record and the balance change are in one transaction, otherwise there is a window between them again:
BEGIN;
INSERTINTO processed_messages (message_id)
VALUES ('m-123')
ONCONFLICTDONOTHING;
-- 0 rows inserted: a duplicate, ROLLBACK and send the ackUPDATE accounts SET balance = balance + 30WHERE id = 'acc_2';
COMMIT;
The same message twice: what happens to the balance
Without an id check
Delivery
message_id
balance
start
-
100
1
m-123
130
2
m-123
160 extra +30
With a processed_messages table
Delivery
INSERT
balance
start
-
100
1
1 row
130
2
0 rows
130 duplicate skipped
Figure 2. The starting balance of acc_2 is 100. Without the id table the second delivery adds 30 more; with it the insert adds no row and the balance does not change.
Example: a duplicate test. The test publishes the same message twice and checks that the credit happened once. The result is asynchronous, so we wait for a stable state instead of a fixed pause:
test('a duplicate message credits the account once', async ({ request }) => {
const before = awaitbalanceOf(request, 'acc_2');
const msg = { messageId: 'm-' + Date.now(), account: 'acc_2', amount: 30 };
awaitpublish('credits', msg);
awaitpublish('credits', msg); // the same messageId againawait expect.poll(() => balanceOf(request, 'acc_2')).toBe(before + 30);
// give a wrongly written consumer time to apply the second copyawaitnewPromise((r) => setTimeout(r, 3000));
expect(awaitbalanceOf(request, 'acc_2')).toBe(before + 30);
});
(publish and balanceOf here are project helpers.) The last pause is deliberate: the test checks the absence of an event and there is otherwise nothing to wait for. This is the only case where a fixed pause is justified, and it should be a short margin, not the main mechanism.
Other concepts.
DLQ (dead letter queue): where messages go that could not be processed after N attempts. They must not be ignored: in fintech this is stuck money, so DLQ length needs an alert and re-processing needs a procedure.
Ordering. In Kafka the order is guaranteed only within a partition. If events of one account go to different partitions, a "debit" may be processed before a "top-up". The usual solution: the message key by account id.
Consumer lag: how many messages are waiting to be processed. A metric for monitoring and for load tests.
Poison message. A message that always fails on processing. It must go to the DLQ after a few attempts and not block the queue or loop forever.
Two ways to process a message
Wrong
Just add the amount
A redelivery adds 30 again. The balance diverges from reality without a single error in the logs.
Right
Check the id and change the balance together
The processed message ids and the balance change in one transaction. A duplicate is skipped.
Figure 3. An idempotent consumer is the answer to at-least-once.
Limits and alternatives. The table of processed ids grows, so it needs cleanup by age; the period must exceed the maximum time within which a message can still be redelivered. Sometimes idempotence comes from the nature of the operation (setting the status to "COMPLETED" is safer than adding an amount), and a separate table is not needed. The more expensive the error, the more worth choosing transactional approaches, for example an outbox: the event is written in the same transaction as the data change and a separate process publishes it to the queue.
Common mistakes.
Assuming a queue guarantees exactly one delivery: without an idempotent consumer it is hidden doubling of money.
Not testing a consumer crash between processing and acknowledgement.
Not watching the DLQ: messages quietly accumulate.
Assuming a global message order: it exists only within a partition or a FIFO group.
Check yourself
A consumer reads a message, credits the money and then sends an ack. It crashes between the credit and the ack. What happens and how to avoid doubling?
Answer
The queue received no ack and will deliver the message again, so the money is credited twice. It is avoided with an idempotent consumer: store the ids of processed messages and write the id and the balance change in one transaction, so the duplicate is skipped.
The events of one account, "top-up" and "debit", are processed in the reverse order. Why does it happen in Kafka and what to change?
Answer
In Kafka order is guaranteed only within a partition, and the account's events landed in different partitions. The fix: a message key by account id so all its events go to one partition. The test: send a series of events for an account and check the processing order.
Related lessons: "Idempotency, retries and rate limiting", "Task: how to test a transfer system with a queue", "Eventual consistency and sagas in tests".
In the interview.Junior: In most systems a queue gives at-least-once: a message is not lost but may arrive twice. So the consumer must be idempotent. Middle/Senior: I test a duplicate message, an order violation, a consumer crash between processing and ack, a poison message that must go to the DLQ, and watch consumer lag. For idempotence I want to see the id record and the data change in one transaction, and the outbox pattern for reliable event publishing.