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

System Design › Backend basics: LB, cache, DB, queues

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

Indexfast search / slower writesReplicationmore reads / replication lagShardingmore data / cross-shard operationsTransactionsintegrity / races without locks
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:

CREATE UNIQUE INDEX 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 60
  const results = await Promise.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 statement
UPDATE accounts
SET balance = balance - 60
WHERE id = 'acc_1' AND balance >= 60;
-- 0 rows updated means insufficient funds

-- last line of defence
ALTER TABLE 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.

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.

More articles in this chapter