Questions 21–40 of 50 · 0 of 20 on this page marked learned
21.backend-0021Mediummid
What does at-least-once delivery mean in a message queue, why do duplicates happen, and how do you make a consumer idempotent?
With at-least-once delivery the broker keeps a message until the consumer acknowledges it. If the consumer crashes or is slow after doing the work but before the ack, the message becomes visible again and is delivered a second time. So duplicates are normal, and the consumer must be idempotent: record each message's unique business id with the effect in the same transaction, or use naturally idempotent operations such as upserts. Exactly-once processing is built from at-least-once delivery plus idempotency.
Full answer
Delivery guarantees
At-most-once: acknowledge first, process later. A crash loses the message. No duplicates.
At-least-once: process first, acknowledge after. A crash causes a redelivery, so duplicates are possible. This is the default for SQS, RabbitMQ with manual acks, Kafka with committed offsets after processing.
Exactly-once: only within a closed system (for example Kafka transactions between topics). Across a database and an external API it is built by at-least-once plus idempotent handling.
Why duplicates happen
Crash between the effect and the ack. Visibility timeout shorter than the processing time. Network loss of the ack. Producer retries after a timeout (the first send had succeeded).
Making a consumer idempotent
Put a unique id in every message (an event id or an idempotency key made by the producer, not the broker's delivery id).
Store processed ids in a table with a unique constraint and insert it in the same database transaction as the business change. If the insert conflicts, skip the work and acknowledge.
Or design operations to be idempotent: set a status to a value, upsert by key, "set balance to X" instead of "add 100".
Keep processed ids as long as duplicates can arrive (retention of the broker plus a margin).
Also set the visibility timeout above the p99 processing time, extend it for long jobs, and make ack the last step.
javascript
// A queue with a visibility timeout, like SQS. Time is a number that we move by hand.
class Queue {
constructor(visibilityTimeout) { this.timeout = visibilityTimeout; this.messages = []; }
send(body) { this.messages.push({ body, visibleAt: 0, receiveCount: 0 }); }
receive(now) {
const m = this.messages.find((x) => x.visibleAt <= now);
if (!m) return null;
m.visibleAt = now + this.timeout; m.receiveCount++;
return m;
}
ack(m) { this.messages = this.messages.filter((x) => x !== m); }
}
function run(label, handler) {
const queue = new Queue(30);
queue.send({ id: 'pay-1001', account: 'A', amount: 100 });
const state = { balance: 0, seen: new Set() };
let m = queue.receive(0);
handler(state, m.body); // the effect is applied...
/* ...and the consumer crashes here, before queue.ack(m) */
console.log(label, '| at t=5 visible again?', queue.receive(5) !== null);
m = queue.receive(31); // after the visibility timeout the message returns
console.log(label, '| at t=31 redelivered, receiveCount =', m.receiveCount);
handler(state, m.body);
queue.ack(m);
console.log(label, '| final balance =', state.balance, '| messages left =', queue.messages.length);
}
run('naive consumer ', (state, msg) => { state.balance += msg.amount; });
run('idempotent consumer', (state, msg) => { if (state.seen.has(msg.id)) return; state.seen.add(msg.id); state.balance += msg.amount; });
The queue and the clock are simulated, so the redelivery happens at a known moment. In a real system the 'seen' set is a database table with a unique constraint, updated in the same transaction as the balance. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
naive consumer | at t=5 visible again? false
naive consumer | at t=31 redelivered, receiveCount = 2
naive consumer | final balance = 200 | messages left = 0
idempotent consumer | at t=5 visible again? false
idempotent consumer | at t=31 redelivered, receiveCount = 2
idempotent consumer | final balance = 100 | messages left = 0
Key points
Process first, acknowledge last gives at-least-once delivery.
Crashes, timeouts and producer retries create duplicates.
Idempotent consumers record the message id in the same transaction as the effect.
Prefer operations that are naturally idempotent.
Exactly-once effects come from at-least-once plus idempotency.
Common mistakes
Acknowledging before the work is done and calling it reliable.
Using the broker's delivery id instead of a business id for deduplication.
Deduplicating in memory only (lost on restart).
A visibility timeout shorter than the job.
Keeping dedup records for too short a time.
Follow-ups
How does Kafka's offset commit relate to at-least-once?
How do SQS FIFO queues deduplicate?
Why is 'exactly once' often a marketing term?
Tips
Define the three guarantees.
Say 'ack last, dedupe by id'.
Explain the crash window.
22.backend-0022Mediummid
How do retries with exponential backoff and a dead-letter queue (DLQ) protect a message consumer from poison messages?
A poison message is one that always fails (bad data, a bug). If the queue redelivers it forever, it burns capacity and may block others. Retry a limited number of times with exponential backoff (and jitter), then move the message to a dead-letter queue (DLQ) with its error details. Alert on DLQ depth, inspect the messages, fix the cause, and redrive them. Distinguish transient errors (retry) from permanent errors (send to the DLQ at once).
Full answer
Flow
The consumer fails to process a message. It does not ack. The message returns to the queue after a delay.
The delay grows with each attempt: base * 2^(attempt - 1) (for example 5 s, 10 s, 20 s), with random jitter to avoid retry waves.
After maxReceiveCount attempts, the broker (SQS redrive policy, RabbitMQ dead-letter exchange) or the consumer moves the message to the DLQ.
Someone is alerted. The team inspects the payload and error, fixes the code or data, and redrives the messages to the main queue.
Good practice
Classify errors: validation failure or unknown type is permanent (straight to the DLQ). A timeout or a 503 from a dependency is transient (retry).
Keep the original message, attempt count, error message and timestamps in the DLQ.
Put an alert on DLQ depth and on the age of the oldest message. A DLQ nobody watches is a silent loss.
Retries make duplicates, so the consumer must be idempotent.
Set a retention on the DLQ that is long enough for investigation. Test redrive in staging.
Protect dependencies with a circuit breaker instead of letting every retry hit a failing service.
javascript
const MAX_RECEIVES = 3;
const backoff = (receiveCount) => 5 * 2 ** (receiveCount - 1); // 5 s, 10 s, 20 s (add jitter in real systems)
const queue = [
{ id: 'welcome-email-1', payload: { to: 'asha@example.com' }, visibleAt: 0, receives: 0 },
{ id: 'welcome-email-2', payload: { to: 'not-an-email' }, visibleAt: 0, receives: 0 }, // a poison message
{ id: 'welcome-email-3', payload: { to: 'ravi@example.com' }, visibleAt: 0, receives: 0 },
];
const dlq = [], done = [], log = [];
let fixed = false;
const handler = (msg) => { if (!/@/.test(msg.payload.to) && !fixed) throw new Error('invalid address'); };
function tick(now) {
const msg = queue.find((m) => m.visibleAt <= now);
if (!msg) return;
msg.receives++;
try { handler(msg); done.push(msg.id); queue.splice(queue.indexOf(msg), 1); }
catch (err) {
if (msg.receives >= MAX_RECEIVES) {
queue.splice(queue.indexOf(msg), 1);
dlq.push({ ...msg, lastError: err.message });
log.push(`t=${now}s ${msg.id}: attempt ${msg.receives} failed, moved to the DLQ`);
} else {
msg.visibleAt = now + backoff(msg.receives);
log.push(`t=${now}s ${msg.id}: attempt ${msg.receives} failed, retry in ${backoff(msg.receives)}s`);
}
}
}
for (let now = 0; now <= 60; now++) tick(now);
console.log(log.join('\n'));
console.log('processed :', done.join(', '));
console.log('dead letter :', dlq.map((m) => `${m.id} (${m.receives} attempts, "${m.lastError}")`).join(', '));
console.log('main queue left :', queue.length);
// After the bug or the data is fixed, redrive the DLQ.
fixed = true;
while (dlq.length) { const m = dlq.shift(); m.receives = 0; m.visibleAt = 0; queue.push(m); }
for (let now = 61; now <= 65; now++) tick(now);
console.log('after redrive :', done.join(', '), '| dead letter =', dlq.length);
Simulated time in seconds. One message always fails until the 'fix', and the backoff, DLQ move and redrive are printed in order. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
t=1s welcome-email-2: attempt 1 failed, retry in 5s
t=6s welcome-email-2: attempt 2 failed, retry in 10s
t=16s welcome-email-2: attempt 3 failed, moved to the DLQ
processed : welcome-email-1, welcome-email-3
dead letter : welcome-email-2 (3 attempts, "invalid address")
main queue left : 0
after redrive : welcome-email-1, welcome-email-3, welcome-email-2 | dead letter = 0
Key points
Limit retries and back off between attempts.
Move messages that keep failing to a DLQ.
Separate transient from permanent errors.
Alert on DLQ depth and redrive after the fix.
Retries need idempotent consumers.
Common mistakes
Retrying forever with no limit.
Retrying immediately in a loop, hammering a failing dependency.
A DLQ with no alert.
Dropping failed messages instead of keeping them.
Retrying permanent errors.
Follow-ups
How does SQS manage the redrive policy?
What is jitter and why add it?
How would you handle a message that fails because a downstream service is down for an hour?
Tips
Walk through attempt, delay, DLQ, redrive.
Separate transient from permanent errors.
Mention alerts.
23.backend-0023Hardsenior
How can you keep message ordering when you scale out consumers, and what do partition keys (or message groups) guarantee?
A single queue with many parallel consumers loses ordering, because a slower worker finishes an earlier message after a faster worker finishes a later one. Brokers give ordering per partition (Kafka), per message group (SQS FIFO) or per queue with one consumer (RabbitMQ). The pattern: choose a partition key (account id, order id), send all messages with the same key to the same partition, and process each partition one message at a time. You get order per key and parallelism across keys, not a global order.
Full answer
The problem
With a shared queue and N workers, messages are taken in order but finish in any order. "Update email" followed by "delete account" can run backwards.
Retries also break order: message 1 fails and is retried after message 2 has succeeded.
Partitioning
The producer computes partition = hash(key) mod partitionCount. All messages with the same key land in the same partition, which keeps their order. Each partition is read by one consumer at a time in a consumer group, one message after another.
Throughput scales with the number of partitions, and a hot key can overload one partition.
Changing the partition count changes the mapping, so plan it in advance.
Practical rules
Define what really needs order: per entity (one order's events), almost never global.
Make consumers tolerant: put a version or sequence number in each message and ignore messages older than the stored version. This also handles duplicates and late arrivals.
A failing message in a partition blocks later messages for that key (head of line blocking). Decide: pause, retry with limits, or move it aside to a DLQ and accept the order impact.
Use idempotent consumers, because redelivery after a crash replays a partition from the last committed offset.
javascript
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const events = [
{ key: 'account-1', seq: 1, ms: 240, name: 'create' },
{ key: 'account-1', seq: 2, ms: 40, name: 'rename' },
{ key: 'account-2', seq: 1, ms: 80, name: 'create' },
{ key: 'account-1', seq: 3, ms: 20, name: 'delete' },
];
const handle = async (e, log) => { await sleep(e.ms); log.push(e); };
const perKey = (log) => Object.entries(log.reduce((acc, e) => ((acc[e.key] ??= []).push(e.seq), acc), {})).map(([k, v]) => `${k}: ${v.join(',')}`).join(' | ');
(async () => {
// 1. One shared queue, three parallel workers.
const shared = [...events], log1 = [];
await Promise.all(Array.from({ length: 3 }, async () => { while (shared.length) await handle(shared.shift(), log1); }));
console.log('shared queue, 3 workers ->', perKey(log1), '(account-1 is out of order)');
// 2. Partitioned by key: each partition is processed one message at a time.
const partitionCount = 3;
const hash = (key) => [...key].reduce((h, c) => h + c.charCodeAt(0), 0) % partitionCount;
const partitions = Array.from({ length: partitionCount }, () => []);
events.forEach((e) => partitions[hash(e.key)].push(e));
const log2 = [];
await Promise.all(partitions.map(async (list) => { for (const e of list) await handle(e, log2); }));
console.log('partitioned by key ->', perKey(log2), '(in order per key)');
console.log('same key, same partition:', hash('account-1') === hash('account-1'), '| partitions used:', partitions.filter((p) => p.length).length);
// 3. A sequence number makes consumers safe against old messages.
const stored = { version: 0 };
const apply = (e) => (e.seq > stored.version ? ((stored.version = e.seq), 'applied') : 'ignored (older or duplicate)');
console.log('apply seq 2, then 1, then 2 again:', [2, 1, 2].map((seq) => apply({ seq })).join(' | '));
})();
Real timers with 20 ms or more between the finishing times, so the order of completion is stable. Kafka and SQS FIFO implement the partition idea inside the broker. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
shared queue, 3 workers -> account-1: 2,3,1 | account-2: 1 (account-1 is out of order)
partitioned by key -> account-2: 1 | account-1: 1,2,3 (in order per key)
same key, same partition: true | partitions used: 2
apply seq 2, then 1, then 2 again: applied | ignored (older or duplicate) | ignored (older or duplicate)
Key points
Parallel consumers on one queue do not keep order.
A partition key keeps order per entity and allows parallelism across entities.
A partition is processed sequentially by one consumer.
Sequence numbers let consumers detect old or duplicate messages.
A failing message can block its partition.
Common mistakes
Expecting a global order from a parallel system.
Using a random or missing partition key.
A hot key that sends most traffic to one partition.
Changing the partition count without a plan.
Letting a retry jump over later messages of the same key.
Follow-ups
How do SQS FIFO message groups work?
What is head-of-line blocking?
How would you handle ordering across two different keys?
Tips
State the guarantee per key.
Explain why parallel workers reorder.
Mention version numbers.
24.backend-0024Hardsenior
What is the transactional outbox pattern, what problem does it solve, and how do you implement the relay with PostgreSQL?
When a service must update its database and publish an event, doing both separately (dual write) can lose the event or publish an event for a change that rolled back. The outbox pattern writes the business change and an event row in the same database transaction. A separate relay reads unpublished rows (FOR UPDATE SKIP LOCKED), publishes them to the broker, and marks them published. If the relay crashes after publishing but before marking, the event is sent again, so consumers must deduplicate by event id (at-least-once).
Full answer
The dual write problem
Save the order, then publish OrderPlaced. If the process dies in between, the order exists and the event never leaves. If you publish first and the database commit fails, you published an event for something that did not happen. There is no transaction across a database and a broker.
Outbox
In one transaction: insert the order and insert a row into an outbox table (event id, type, payload, created_at, published_at null). Either both commit or neither.
A relay process (a poller, or change data capture such as Debezium reading the write-ahead log) reads unpublished rows in order, publishes them, and sets published_at.
The relay selects with FOR UPDATE SKIP LOCKED, so several relay instances can run without taking the same rows.
Delivery is at least once: a crash between publish and update repeats the event. The event id is the deduplication key for consumers (see the idempotent consumer item).
Operations
Add an index on unpublished rows (a partial index where published_at is null). Delete or archive old published rows.
Preserve order per aggregate by selecting in id order and publishing with the aggregate id as partition key.
Monitor the lag (oldest unpublished row).
javascript
const { Client } = require('pg');
(async () => {
const db = new Client(); await db.connect();
await db.query(`
DROP TABLE IF EXISTS bk24_outbox; DROP TABLE IF EXISTS bk24_orders;
CREATE TABLE bk24_orders (id serial PRIMARY KEY, item text NOT NULL);
CREATE TABLE bk24_outbox (id serial PRIMARY KEY, event_id uuid NOT NULL DEFAULT gen_random_uuid(), payload jsonb NOT NULL, published_at timestamptz);`);
async function placeOrder(item, fail = false) {
try {
await db.query('BEGIN');
const { rows } = await db.query('INSERT INTO bk24_orders (item) VALUES ($1) RETURNING id', [item]);
await db.query('INSERT INTO bk24_outbox (payload) VALUES ($1)', [JSON.stringify({ type: 'OrderPlaced', orderId: rows[0].id, item })]);
if (fail) throw new Error('payment failed');
await db.query('COMMIT');
} catch (err) { await db.query('ROLLBACK'); }
}
await placeOrder('book'); await placeOrder('pen'); await placeOrder('lamp', true);
const count = async (t) => (await db.query(`SELECT count(*)::int AS n FROM ${t}`)).rows[0].n;
console.log('orders, outbox rows (the failed order left no event):', await count('bk24_orders'), await count('bk24_outbox'));
const broker = [];
async function relay({ crashAfterFirstPublish = false } = {}) {
await db.query('BEGIN');
const { rows } = await db.query('SELECT id, event_id, payload FROM bk24_outbox WHERE published_at IS NULL ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 10');
for (const row of rows) {
broker.push({ eventId: row.event_id, ...row.payload }); // publish
if (crashAfterFirstPublish) { await db.query('ROLLBACK'); return 'relay crashed after publishing 1 event, before marking it'; }
await db.query('UPDATE bk24_outbox SET published_at = now() WHERE id = $1', [row.id]);
}
await db.query('COMMIT');
return `relay published ${rows.length} event(s)`;
}
console.log(await relay({ crashAfterFirstPublish: true }));
console.log(await relay());
console.log('messages on the broker:', broker.length, '| distinct event ids:', new Set(broker.map((m) => m.eventId)).size);
// The consumer deduplicates by event id.
const processed = new Set(); let effects = 0;
for (const m of broker) if (!processed.has(m.eventId)) { processed.add(m.eventId); effects++; }
console.log('consumer effects after dedup:', effects);
await db.query('DROP TABLE bk24_outbox; DROP TABLE bk24_orders');
await db.end();
})();
Runs on the local PostgreSQL. The broker is an array, and the relay crash is simulated by a rollback after the first publish. Only one relay ran, so the effect of SKIP LOCKED with several relays is described in the text, not run. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
orders, outbox rows (the failed order left no event): 2 2
relay crashed after publishing 1 event, before marking it
relay published 2 event(s)
messages on the broker: 3 | distinct event ids: 2
consumer effects after dedup: 2
Key points
Write the data and the event in one local transaction.
A relay publishes outbox rows and marks them done.
SKIP LOCKED lets many relays work without conflicts.
Publishing is at least once, so consumers deduplicate by event id.
Monitor outbox lag and clean old rows.
Common mistakes
Publishing to the broker inside the database transaction.
Assuming the outbox gives exactly-once delivery.
Never cleaning the outbox table.
A polling relay with no index, scanning the whole table.
Publishing events out of order for one aggregate.
Follow-ups
How does change data capture compare with a polling relay?
What is the inbox pattern?
How do you keep order per aggregate?
Tips
Describe the dual write problem first.
Explain 'one transaction, two rows'.
State that delivery is at least once.
25.backend-0025Easyfresher
What is a database index, how does a B-tree index speed up queries, and how do you check with EXPLAIN that a query uses it?
An index is a separate, sorted structure (usually a B-tree) that maps column values to row locations, so the database can find rows in logarithmic time instead of reading the whole table (a sequential scan). It speeds up equality, range and ORDER BY queries on the indexed column, but costs disk space and slows inserts, updates and deletes, because each index must be maintained. EXPLAIN shows the plan: Seq Scan, Index Scan, Bitmap Heap Scan or Index Only Scan.
Full answer
How a B-tree helps
Keys are kept sorted in a balanced tree of pages. A lookup walks from the root to a leaf in a few steps (three or four levels cover millions of rows) and then jumps to the table row.
Because keys are sorted, the same index serves equality (=), ranges (<, BETWEEN), sorting (ORDER BY with LIMIT) and prefix matching.
Primary keys and unique constraints create an index automatically. Foreign keys do not, in PostgreSQL, so add one when you join or delete by that column.
Costs
Every index uses space and must be updated on each write. Too many indexes slow writes. Index what your queries filter, join and sort on, and remove unused ones.
The planner decides by estimated cost. For a query that returns most rows, reading the table in order is cheaper, so a sequential scan is correct.
Checking
EXPLAIN shows the plan without running the query. EXPLAIN ANALYZE runs it and shows real rows and time. Look for the scan type on big tables, the estimated against actual row counts, and extra Sort steps.
Run ANALYZE so the planner has fresh statistics.
sql
SET client_min_messages = warning;
DROP TABLE IF EXISTS idx_students;
CREATE TABLE idx_students (id serial PRIMARY KEY, email text NOT NULL, city text NOT NULL, score int NOT NULL);
INSERT INTO idx_students (email, city, score)
SELECT 'user' || g || '@example.com', (ARRAY['Pune','Delhi','Goa','Chennai'])[1 + g % 4], g % 100
FROM generate_series(1, 50000) g;
ANALYZE idx_students;
\echo 1. no index on email
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE email = 'user777@example.com';
CREATE INDEX idx_students_email ON idx_students (email);
ANALYZE idx_students;
\echo 2. with an index on email
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE email = 'user777@example.com';
\echo 3. the primary key is indexed automatically
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE id = 10;
\echo 4. ORDER BY with LIMIT can read the index in order
EXPLAIN (COSTS OFF) SELECT * FROM idx_students ORDER BY email LIMIT 3;
\echo 5. a query that returns almost every row is better served by a table scan
EXPLAIN (COSTS OFF) SELECT * FROM idx_students WHERE email > 'a';
\echo 6. indexes that must be maintained on every write
SELECT indexname FROM pg_indexes WHERE tablename = 'idx_students' ORDER BY indexname;
DROP TABLE idx_students;
Run with psql against the local PostgreSQL 17 server. COSTS OFF keeps the plans short and stable. Real timings were not measured here. Save it as app.sql and run it with psql -f app.sql.
Output (PostgreSQL 17 via psql, run once):
1. no index on email
QUERY PLAN
-------------------------------------------------
Seq Scan on idx_students
Filter: (email = 'user777@example.com'::text)
(2 rows)
2. with an index on email
QUERY PLAN
-----------------------------------------------------
Index Scan using idx_students_email on idx_students
Index Cond: (email = 'user777@example.com'::text)
(2 rows)
3. the primary key is indexed automatically
QUERY PLAN
----------------------------------------------------
Index Scan using idx_students_pkey on idx_students
Index Cond: (id = 10)
(2 rows)
4. ORDER BY with LIMIT can read the index in order
QUERY PLAN
-----------------------------------------------------------
Limit
-> Index Scan using idx_students_email on idx_students
(2 rows)
5. a query that returns almost every row is better served by a table scan
QUERY PLAN
-------------------------------
Seq Scan on idx_students
Filter: (email > 'a'::text)
(2 rows)
6. indexes that must be maintained on every write
indexname
--------------------
idx_students_email
idx_students_pkey
(2 rows)
Key points
An index is a sorted structure that avoids scanning the whole table.
B-trees support equality, range, ordering and prefixes.
Each index costs space and write time.
Primary and unique keys are indexed; foreign keys are not automatically.
Read EXPLAIN output to confirm the plan.
Common mistakes
Indexing every column.
Expecting an index to be used for a query that returns most of the table.
Forgetting to index foreign keys used in joins.
Reading EXPLAIN without running ANALYZE first.
Adding indexes in production with a blocking CREATE INDEX instead of CONCURRENTLY.
Follow-ups
What is CREATE INDEX CONCURRENTLY?
How does a hash index differ from a B-tree?
How do you find unused indexes?
Tips
Say 'sorted structure, logarithmic lookup'.
Mention write costs.
Name the scan types.
26.backend-0026Mediummid
How do composite (multi-column) indexes work, why does column order matter, and what is the leftmost prefix rule?
A composite index sorts rows by the first column, then by the second within equal first values, and so on. It can serve conditions on the leading columns (the leftmost prefix) efficiently: (a), (a, b) and (a, b, c) filters, but a filter on b alone cannot use the sorted order well. Put equality columns first, then the column used for range or sorting, and order them by how the queries filter. The right order can also remove a sort step for ORDER BY ... LIMIT.
Full answer
How it is stored
Index (customer_id, status) is like a phone book sorted by last name, then first name. Finding all rows for one customer is fast. Finding all rows for one status needs a scan of the whole book.
Rules of thumb
Leftmost prefix: the index helps queries that filter on customer_id, or on customer_id and status. For status alone PostgreSQL 17 (no skip scan) can only read the whole index and filter, which is slow or is replaced by a sequential scan.
Put equality conditions first, then range or ORDER BY columns. After a range condition, later columns cannot narrow the search.
Put the most commonly filtered column first, unless a different order serves more queries. A single composite index can replace a single column index on its first column.
For ORDER BY created_at DESC LIMIT 5 per customer, index (customer_id, created_at) lets the database read the newest rows directly, without sorting.
Selectivity matters, but the query shape matters more. A very selective column in second position does not help queries that skip the first column.
Always verify with EXPLAIN on realistic data. The planner may still choose a sequential scan when it expects to read much of the table.
sql
SET client_min_messages = warning;
DROP TABLE IF EXISTS idx_orders;
CREATE TABLE idx_orders (id serial PRIMARY KEY, customer_id int NOT NULL, status text NOT NULL, created_at timestamptz NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO idx_orders (customer_id, status, created_at, total)
SELECT (g % 2000) + 1,
CASE WHEN g % 200 = 0 THEN 'pending' WHEN g % 3 = 0 THEN 'shipped' ELSE 'paid' END,
timestamptz '2026-01-01' + (g || ' minutes')::interval,
(g % 500) + 10
FROM generate_series(1, 100000) g;
CREATE INDEX idx_orders_cust_status ON idx_orders (customer_id, status);
ANALYZE idx_orders;
\echo 1. both columns of the index
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5 AND status = 'paid';
\echo 2. only the leading column
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5;
\echo 3. only the second column: the whole index is read (look at the buffers)
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT * FROM idx_orders WHERE status = 'pending';
CREATE INDEX idx_orders_status_cust ON idx_orders (status, customer_id);
ANALYZE idx_orders;
\echo 4. the same query when an index starts with status: far fewer buffers
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT * FROM idx_orders WHERE status = 'pending';
\echo 5. newest orders of one customer, index (customer_id, status): a Sort is needed
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5 ORDER BY created_at DESC LIMIT 3;
CREATE INDEX idx_orders_cust_created ON idx_orders (customer_id, created_at);
ANALYZE idx_orders;
\echo 6. with index (customer_id, created_at): no Sort
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE customer_id = 5 ORDER BY created_at DESC LIMIT 3;
DROP TABLE idx_orders;
Run with psql on PostgreSQL 17 with 100,000 generated orders. Plans can change with data size and settings, so read the shapes (Index Cond, a Sort node) and compare the Buffers lines of cases 3 and 4. The exact buffer counts and the hit or read split can differ on another machine. Save it as app.sql and run it with psql -f app.sql.
Output (PostgreSQL 17 via psql, run once):
1. both columns of the index
QUERY PLAN
---------------------------------------------------------------------
Bitmap Heap Scan on idx_orders
Recheck Cond: ((customer_id = 5) AND (status = 'paid'::text))
-> Bitmap Index Scan on idx_orders_cust_status
Index Cond: ((customer_id = 5) AND (status = 'paid'::text))
(4 rows)
2. only the leading column
QUERY PLAN
---------------------------------------------------
Bitmap Heap Scan on idx_orders
Recheck Cond: (customer_id = 5)
-> Bitmap Index Scan on idx_orders_cust_status
Index Cond: (customer_id = 5)
(4 rows)
3. only the second column: the whole index is read (look at the buffers)
QUERY PLAN
-----------------------------------------------------------------------------
Bitmap Heap Scan on idx_orders (actual rows=500 loops=1)
Recheck Cond: (status = 'pending'::text)
Heap Blocks: exact=500
Buffers: shared hit=500 read=99
-> Bitmap Index Scan on idx_orders_cust_status (actual rows=500 loops=1)
Index Cond: (status = 'pending'::text)
Buffers: shared read=99
(7 rows)
4. the same query when an index starts with status: far fewer buffers
QUERY PLAN
-----------------------------------------------------------------------------
Bitmap Heap Scan on idx_orders (actual rows=500 loops=1)
Recheck Cond: (status = 'pending'::text)
Heap Blocks: exact=500
Buffers: shared hit=500 read=2
-> Bitmap Index Scan on idx_orders_status_cust (actual rows=500 loops=1)
Index Cond: (status = 'pending'::text)
Buffers: shared read=2
Planning:
Buffers: shared hit=21 read=1
(9 rows)
5. newest orders of one customer, index (customer_id, status): a Sort is needed
QUERY PLAN
---------------------------------------------------------------
Limit
-> Sort
Sort Key: created_at DESC
-> Bitmap Heap Scan on idx_orders
Recheck Cond: (customer_id = 5)
-> Bitmap Index Scan on idx_orders_cust_status
Index Cond: (customer_id = 5)
(7 rows)
6. with index (customer_id, created_at): no Sort
QUERY PLAN
-----------------------------------------------------------------------
Limit
-> Index Scan Backward using idx_orders_cust_created on idx_orders
Index Cond: (customer_id = 5)
(3 rows)
Key points
A composite index is sorted by the first column, then the next.
Leftmost prefix queries can use it; others usually cannot.
Equality columns first, then range or sort columns.
The right order removes a Sort step for ORDER BY with LIMIT.
Check the plan on realistic data.
Common mistakes
Building one index per column and hoping the planner combines them well.
Putting a range column before equality columns.
Leaving duplicate indexes (a and a,b).
Never checking the plan.
Reordering columns in an existing index without checking all queries.
Follow-ups
What is an index skip scan?
How would you index WHERE a = ? AND b > ? ORDER BY c?
How do you find redundant indexes?
Tips
Use the phone book analogy.
State equality first, range next.
Mention ORDER BY with LIMIT.
27.backend-0027Mediummid
What are covering indexes (INCLUDE), index-only scans and partial indexes, and when do you use them?
A covering index contains every column the query needs, so the database can answer from the index alone (an index-only scan) without visiting the table. In PostgreSQL, INCLUDE adds extra payload columns to the index that are not part of the search key. A partial index has a WHERE clause and indexes only the rows that match, so it is smaller, cheaper to maintain and ideal for hot subsets such as pending jobs or active users. Both trade a bit of write cost and space for faster reads.
Full answer
Covering index
Normally the index finds row locations and the engine fetches each row from the table (random reads). If the index also holds the selected columns, no table visit is needed.
CREATE INDEX ON orders (customer_id) INCLUDE (total) keeps total as payload. Use INCLUDE for columns you only select, not filter, so the search key stays small.
In PostgreSQL an index-only scan also needs the visibility map to be current (VACUUM), otherwise it still fetches heap pages. EXPLAIN ANALYZE shows Heap Fetches.
Partial index
CREATE INDEX ON orders (created_at) WHERE status = 'pending'. The index holds only pending rows. Queries must contain a condition that implies the index predicate (status = 'pending') for the planner to use it.
Typical uses: queue tables, soft deleted rows (WHERE deleted_at IS NULL), unique constraints on a subset (UNIQUE (email) WHERE active).
Costs and cautions
Wider indexes use more memory and slow writes. Do not cover everything.
Updates to included columns update the index.
Partial index predicates are fixed at creation, and parameterised queries may not match them.
sql
SET client_min_messages = warning;
DROP TABLE IF EXISTS idx_orders;
CREATE TABLE idx_orders (id serial PRIMARY KEY, customer_id int NOT NULL, status text NOT NULL, created_at timestamptz NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO idx_orders (customer_id, status, created_at, total)
SELECT (g % 2000) + 1,
CASE WHEN g % 200 = 0 THEN 'pending' WHEN g % 3 = 0 THEN 'shipped' ELSE 'paid' END,
timestamptz '2026-01-01' + (g || ' minutes')::interval,
(g % 500) + 10
FROM generate_series(1, 100000) g;
CREATE INDEX idx_orders_cust ON idx_orders (customer_id);
VACUUM ANALYZE idx_orders;
\echo 1. ordinary index: each row is fetched from the table
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT customer_id, total FROM idx_orders WHERE customer_id = 5;
DROP INDEX idx_orders_cust;
CREATE INDEX idx_orders_cust_cov ON idx_orders (customer_id) INCLUDE (total);
VACUUM ANALYZE idx_orders;
\echo 2. covering index: an index-only scan with no heap fetches
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT customer_id, total FROM idx_orders WHERE customer_id = 5;
CREATE INDEX idx_orders_created_all ON idx_orders (created_at);
CREATE INDEX idx_orders_created_pending ON idx_orders (created_at) WHERE status = 'pending';
ANALYZE idx_orders;
\echo 3. a query that matches the partial index condition
EXPLAIN (COSTS OFF) SELECT * FROM idx_orders WHERE status = 'pending' ORDER BY created_at LIMIT 5;
\echo 4. the partial index is much smaller than the full one
SELECT pg_relation_size('idx_orders_created_pending') * 10 < pg_relation_size('idx_orders_created_all') AS partial_is_under_a_tenth;
DROP TABLE idx_orders;
Run with psql on PostgreSQL 17. EXPLAIN ANALYZE is used with timing off so the output is stable. The partial index is about 1 percent of the rows, so the size comparison is safe. Save it as app.sql and run it with psql -f app.sql.
Output (PostgreSQL 17 via psql, run once):
1. ordinary index: each row is fetched from the table
QUERY PLAN
---------------------------------------------------------------------
Bitmap Heap Scan on idx_orders (actual rows=50 loops=1)
Recheck Cond: (customer_id = 5)
Heap Blocks: exact=50
-> Bitmap Index Scan on idx_orders_cust (actual rows=50 loops=1)
Index Cond: (customer_id = 5)
(5 rows)
2. covering index: an index-only scan with no heap fetches
QUERY PLAN
----------------------------------------------------------------------------------
Index Only Scan using idx_orders_cust_cov on idx_orders (actual rows=50 loops=1)
Index Cond: (customer_id = 5)
Heap Fetches: 0
(3 rows)
3. a query that matches the partial index condition
QUERY PLAN
-----------------------------------------------------------------
Limit
-> Index Scan using idx_orders_created_pending on idx_orders
(2 rows)
4. the partial index is much smaller than the full one
partial_is_under_a_tenth
--------------------------
t
(1 row)
Key points
Covering indexes answer queries without visiting the table.
INCLUDE adds payload columns that are not search keys.
Index-only scans need an up-to-date visibility map.
Partial indexes cover a subset of rows and stay small.
Use them for hot, repeated queries.
Common mistakes
Including too many columns and making a huge index.
Expecting an index-only scan on a table that was never vacuumed.
Writing a query that does not imply the partial index predicate.
Using INCLUDE for columns that are used in filters.
Forgetting the write cost of wide indexes.
Follow-ups
What is the visibility map?
How does a unique partial index enforce 'one active row per user'?
How would you find the queries that deserve a covering index?
Tips
Explain 'no table visit'.
Give one use case for a partial index.
Mention VACUUM.
28.backend-0028Hardsenior
Why might PostgreSQL ignore an index you created, and how do you read EXPLAIN (ANALYZE) to find the cause?
The planner picks the cheapest plan from estimates. It ignores an index when the query does not match it (a function on the column, a different expression, a missing leftmost column), when the filter matches a large share of the table so a sequential scan is cheaper, when statistics are stale so the estimate is wrong, or when the table is tiny. Read EXPLAIN ANALYZE for the scan type, estimated against actual rows, loops, and the time per node, then fix the query shape, add the right expression or partial index, or run ANALYZE.
Full answer
Common causes
Function or cast on the column: WHERE lower(email) = 'x' cannot use an index on email. Fix: an expression index on lower(email), or store the data normalised.
Low selectivity: if 99 percent of rows match, a sequential scan is cheaper than an index with many random reads. This is a correct decision.
Leading wildcard: LIKE '%abc' cannot use a B-tree. Use pg_trgm (GIN or GiST) for such searches.
Wrong column order or a missing leading column in a composite index.
Stale or missing statistics after bulk loads: run ANALYZE. Look at estimated rows against actual rows. A big difference (10x or more) is the sign.
Data type or collation mismatches, or OR conditions across different columns (may need UNION or separate indexes).
A tiny table: reading the whole table is faster than using an index.
Reading EXPLAIN (ANALYZE)
Node type (Seq Scan, Index Scan, Bitmap Heap Scan, Index Only Scan), the join type, and sort steps.
rows=... (estimate) and actual rows=... Large gaps point to statistics problems.
loops: a node inside a nested loop runs many times, and the time is per loop.
Rows Removed by Filter: lots of discarded rows suggest a better index.
Do not force the planner with settings in production. Fix the cause instead. Use enable_seqscan = off only as a test to see what the index would cost.
javascript
const { Client } = require('pg');
(async () => {
const db = new Client(); await db.connect();
await db.query(`
DROP TABLE IF EXISTS bk28_users;
CREATE TABLE bk28_users (id serial PRIMARY KEY, email text NOT NULL, active boolean NOT NULL);
INSERT INTO bk28_users (email, active)
SELECT 'User' || g || '@Example.com', g % 100 <> 0 FROM generate_series(1, 100000) g;
CREATE INDEX bk28_email ON bk28_users (email);
CREATE INDEX bk28_active ON bk28_users (active);
ANALYZE bk28_users;`);
// Walks the JSON plan and returns the scan node on the table.
const scanType = async (sql) => {
const { rows } = await db.query('EXPLAIN (FORMAT JSON) ' + sql);
const find = (node) => (node['Relation Name'] ? node['Node Type'] : (node.Plans || []).map(find).find(Boolean));
return find(rows[0]['QUERY PLAN'][0].Plan);
};
const usesIndex = (t) => /Index|Bitmap/.test(t);
const report = async (label, sql) => { const t = await scanType(sql); console.log(label.padEnd(46), t.padEnd(18), 'index used:', usesIndex(t)); };
await report('1. email = value', "SELECT * FROM bk28_users WHERE email = 'User500@Example.com'");
await report('2. lower(email) = value (function on column)', "SELECT * FROM bk28_users WHERE lower(email) = 'user500@example.com'");
await db.query('CREATE INDEX bk28_email_lower ON bk28_users (lower(email)); ANALYZE bk28_users');
await report('3. same query after an expression index', "SELECT * FROM bk28_users WHERE lower(email) = 'user500@example.com'");
await report("4. email LIKE '%500@Example.com' (leading wildcard)", "SELECT * FROM bk28_users WHERE email LIKE '%500@Example.com'");
await report('5. active = true (99 percent of rows)', 'SELECT * FROM bk28_users WHERE active = true');
await report('6. active = false (1 percent of rows)', 'SELECT * FROM bk28_users WHERE active = false');
// Estimated rows against real rows for query 6.
const { rows } = await db.query('EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM bk28_users WHERE active = false');
const node = JSON.parse(JSON.stringify(rows[0]['QUERY PLAN'][0].Plan));
console.log('query 6 estimated rows:', node['Plan Rows'], '| actual rows:', node['Actual Rows']);
await db.query('DROP TABLE bk28_users');
await db.end();
})();
Runs on the local PostgreSQL with 100,000 rows. The script prints scan types read from EXPLAIN (FORMAT JSON) and the estimate against the actual row count for one query. Index and Bitmap scans are both counted as 'index used'. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
1. email = value Index Scan index used: true
2. lower(email) = value (function on column) Seq Scan index used: false
3. same query after an expression index Index Scan index used: true
4. email LIKE '%500@Example.com' (leading wildcard) Seq Scan index used: false
5. active = true (99 percent of rows) Seq Scan index used: false
6. active = false (1 percent of rows) Index Scan index used: true
query 6 estimated rows: 957 | actual rows: 1000
Key points
The planner chooses by estimated cost, not by index existence.
A function on the column needs an expression index.
Unselective filters are correctly served by sequential scans.
Compare estimated and actual rows to spot bad statistics.
Fix the cause rather than forcing plans.
Common mistakes
Rewriting queries with functions on indexed columns.
Forcing the planner with settings in production.
Skipping ANALYZE after a bulk load.
Reading only the top plan node.
Adding indexes for queries that return most of the table.
Follow-ups
What does Rows Removed by Filter tell you?
How does pg_trgm help with LIKE '%text%'?
What is auto_explain?
Tips
List causes by group: shape, selectivity, statistics.
Say 'estimated against actual rows'.
Avoid forcing plans.
29.backend-0029Easyfresher
What does ACID mean for database transactions, and how do you use a transaction to make a multi-step change all-or-nothing?
ACID stands for Atomicity (all steps happen or none), Consistency (constraints are respected, so the data moves from one valid state to another), Isolation (concurrent transactions do not see each other's half-done work, to a degree set by the isolation level) and Durability (committed data survives crashes). Wrap related statements in BEGIN and COMMIT. If any statement fails, ROLLBACK undoes all of them. Savepoints let you undo part of a transaction.
Full answer
Atomicity: a money transfer is two updates (debit and credit). Without a transaction a crash between them loses money. With a transaction both apply or neither does.
Consistency: the database enforces rules (NOT NULL, foreign keys, CHECK balance >= 0). A statement that breaks a rule fails and the transaction cannot commit as is. Your application rules (for example "total stays the same") are your responsibility.
Isolation: other sessions see the old values until you commit (details depend on the isolation level, see the next items).
Durability: after COMMIT returns, the change is in the write-ahead log on disk, so it survives a crash.
How to use them
Keep transactions short. Do not wait for a user or a slow external call inside one, because open transactions hold locks and block cleanup (vacuum).
In PostgreSQL, an error inside a transaction puts it in an aborted state: you must ROLLBACK (or roll back to a savepoint) before running more statements.
SAVEPOINT name and ROLLBACK TO name undo a part (for example one optional step) while keeping the earlier work.
One statement is already atomic by itself. Use a transaction when several statements must succeed together.
Handle retries for serialisation failures and deadlocks (error codes 40001 and 40P01).
javascript
const { Client } = require('pg');
(async () => {
const db = new Client(); await db.connect();
await db.query(`
DROP TABLE IF EXISTS bk29_accounts;
CREATE TABLE bk29_accounts (id int PRIMARY KEY, balance int NOT NULL CHECK (balance >= 0));
INSERT INTO bk29_accounts VALUES (1, 100), (2, 50);`);
const balances = async () => (await db.query('SELECT balance FROM bk29_accounts ORDER BY id')).rows.map((r) => r.balance).join(', ');
async function transfer(from, to, amount) {
try {
await db.query('BEGIN');
await db.query('UPDATE bk29_accounts SET balance = balance - $1 WHERE id = $2', [amount, from]);
await db.query('UPDATE bk29_accounts SET balance = balance + $1 WHERE id = $2', [amount, to]);
await db.query('COMMIT');
return 'committed';
} catch (err) {
await db.query('ROLLBACK');
return `rolled back (${err.code} ${err.constraint})`;
}
}
console.log('start :', await balances());
console.log('transfer 30 from 1 to 2 :', await transfer(1, 2, 30), '->', await balances());
console.log('transfer 500 from 1 to 2 :', await transfer(1, 2, 500), '->', await balances(), '(the credit was never kept)');
// Without a transaction, the first statement stays even when the second fails.
await db.query('UPDATE bk29_accounts SET balance = balance + 10 WHERE id = 2');
await db.query('UPDATE bk29_accounts SET balance = balance - 999 WHERE id = 1').catch(() => {});
console.log('no transaction, second fails:', await balances(), '(only half of the change happened)');
// A savepoint undoes only the failing part.
await db.query('BEGIN');
await db.query('UPDATE bk29_accounts SET balance = balance + 1 WHERE id = 1');
await db.query('SAVEPOINT optional_step');
await db.query('UPDATE bk29_accounts SET balance = balance - 1000 WHERE id = 2').catch(() => {});
await db.query('ROLLBACK TO optional_step');
await db.query('COMMIT');
console.log('with a savepoint :', await balances(), '(first change kept)');
await db.query('DROP TABLE bk29_accounts');
await db.end();
})();
Runs on the local PostgreSQL. A CHECK constraint makes the second step fail, so the effect of ROLLBACK and of missing transactions can be seen in the balances. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
start : 100, 50
transfer 30 from 1 to 2 : committed -> 70, 80
transfer 500 from 1 to 2 : rolled back (23514 bk29_accounts_balance_check) -> 70, 80 (the credit was never kept)
no transaction, second fails: 70, 90 (only half of the change happened)
with a savepoint : 71, 90 (first change kept)
Key points
Atomicity: all or nothing.
Consistency: constraints keep data valid.
Isolation limits what concurrent transactions can see.
Durability: committed data survives crashes.
Keep transactions short and handle errors with ROLLBACK.
Common mistakes
Doing multi-step changes without a transaction.
Holding a transaction open while calling a payment API.
Ignoring the aborted transaction state after an error.
Assuming isolation is perfect by default.
Swallowing errors and committing anyway.
Follow-ups
What does the write-ahead log do?
What is the default isolation level in PostgreSQL?
What happens to a transaction if the connection drops?
Tips
Spell out ACID with one example each.
Use the bank transfer.
Mention short transactions.
30.backend-0030Mediummid
What are the transaction isolation levels and the anomalies they prevent (dirty read, non-repeatable read, phantom), and how does PostgreSQL behave at READ COMMITTED and REPEATABLE READ?
Isolation levels trade correctness for concurrency. READ COMMITTED (the PostgreSQL default) shows each statement the data committed before that statement began, so the same query can return different results inside one transaction (non-repeatable read). REPEATABLE READ uses one snapshot for the whole transaction, so reads are stable, and PostgreSQL aborts a transaction that tries to update a row changed since its snapshot (serialization failure 40001). SERIALIZABLE adds detection of other anomalies such as write skew. PostgreSQL never allows dirty reads.
Full answer
Anomalies
Dirty read: reading data another transaction has not committed. PostgreSQL does not allow it at any level (READ UNCOMMITTED behaves like READ COMMITTED).
Non-repeatable read: reading the same row twice and seeing a changed value because another transaction committed in between.
Phantom read: running the same range query twice and seeing new rows. (PostgreSQL REPEATABLE READ prevents this too, because it uses a snapshot.)
Lost update and write skew: two transactions read, then write based on stale reads. Need locks, atomic updates, version checks or SERIALIZABLE.
Levels in PostgreSQL (MVCC, readers do not block writers)
READ COMMITTED: a new snapshot per statement. UPDATE waits for a conflicting row lock, then re-checks the row.
REPEATABLE READ: one snapshot per transaction. A write to a row that changed after the snapshot fails with SQLSTATE 40001, and the application retries the transaction.
SERIALIZABLE: guarantees results as if transactions ran one at a time, using predicate tracking. It can abort transactions with 40001, so every write path needs retry logic.
Choosing: READ COMMITTED with explicit locking or atomic SQL is common. Use REPEATABLE READ for consistent reports. Use SERIALIZABLE when invariants span several rows and you accept retries.
javascript
const { Client } = require('pg');
(async () => {
const a = new Client(), b = new Client();
await Promise.all([a.connect(), b.connect()]);
const reset = () => a.query('DROP TABLE IF EXISTS bk30_acct; CREATE TABLE bk30_acct (id int PRIMARY KEY, balance int); INSERT INTO bk30_acct VALUES (1, 100)');
const read = async (c) => (await c.query('SELECT balance FROM bk30_acct WHERE id = 1')).rows[0].balance;
// 1. No dirty reads: B does not see A's uncommitted update.
await reset();
await a.query('BEGIN'); await a.query('UPDATE bk30_acct SET balance = 10 WHERE id = 1');
console.log('1. B reads while A is uncommitted :', await read(b), '(no dirty read)');
await a.query('ROLLBACK');
// 2. READ COMMITTED: a non-repeatable read.
await reset();
await a.query('BEGIN ISOLATION LEVEL READ COMMITTED');
const first = await read(a);
await b.query('UPDATE bk30_acct SET balance = 70 WHERE id = 1'); // B commits (autocommit)
const second = await read(a);
await a.query('COMMIT');
console.log('2. READ COMMITTED reads :', first, 'then', second, '(non-repeatable read)');
// 3. REPEATABLE READ: the snapshot is stable, and a conflicting write fails.
await reset();
await a.query('BEGIN ISOLATION LEVEL REPEATABLE READ');
const r1 = await read(a);
await b.query('UPDATE bk30_acct SET balance = 70 WHERE id = 1');
const r2 = await read(a);
console.log('3. REPEATABLE READ reads :', r1, 'then', r2, '(same snapshot)');
try { await a.query('UPDATE bk30_acct SET balance = balance + 1 WHERE id = 1'); console.log(' update succeeded'); }
catch (err) { console.log(' update after a concurrent change :', err.code, '-', err.message); }
await a.query('ROLLBACK');
await a.query('DROP TABLE bk30_acct');
await Promise.all([a.end(), b.end()]);
})();
Two connections are interleaved by hand against the local PostgreSQL server. The order of statements is fixed, so the anomalies appear every time. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
1. B reads while A is uncommitted : 100 (no dirty read)
2. READ COMMITTED reads : 100 then 70 (non-repeatable read)
3. REPEATABLE READ reads : 100 then 100 (same snapshot)
update after a concurrent change : 40001 - could not serialize access due to concurrent update
Key points
Higher isolation means fewer anomalies and more aborts or waiting.
PostgreSQL has no dirty reads at any level.
READ COMMITTED can show different data to two statements in one transaction.
REPEATABLE READ gives a stable snapshot and may raise 40001.
Applications must retry serialization failures.
Common mistakes
Assuming the default level protects against lost updates.
Not retrying after SQLSTATE 40001.
Running long reports at READ COMMITTED and expecting a consistent view.
Using SERIALIZABLE without retry code.
Believing that the SQL standard names describe every database in the same way.
Follow-ups
What is MVCC?
How does READ COMMITTED treat an UPDATE that waits on a locked row?
When would you use SERIALIZABLE?
Tips
Name the anomalies with one-line examples.
State PostgreSQL's default and its behaviour.
Mention retries.
31.backend-0031Hardsenior
What is write skew, why do REPEATABLE READ snapshots not prevent it, and how does SERIALIZABLE isolation fix it in PostgreSQL?
Write skew happens when two transactions read the same data, each decides that a rule still holds, and then update different rows, so that together they break the rule. Snapshot isolation (REPEATABLE READ in PostgreSQL) does not detect it because the updated rows do not overlap. SERIALIZABLE tracks read and write dependencies and aborts one of the transactions with SQLSTATE 40001. The application retries it, and the retry sees the new state and refuses the change.
Full answer
Example: a hospital rule says at least one doctor must stay on call. Alice and Bob are both on call. Each runs: read the number on call (2), see that it is safe to leave, set own on_call to false. Run at the same time, both see 2, both update their own row, and both commit. Nobody is on call.
Why other levels miss it
No row is updated by both transactions, so there is no write-write conflict to detect. Each transaction's snapshot was consistent when it read, but the combined result is not valid.
Fixes
SERIALIZABLE: the database detects the dangerous dependency cycle (each transaction read data the other changed) and aborts one with 40001 (serialization_failure). Retry the whole transaction. Keep transactions short, because the tracking has a cost and can produce false positives.
Explicit locking: lock the rows that form the rule (SELECT ... FOR UPDATE on all on-call rows, or on a parent row), so the transactions run one after the other.
Constraints: model the rule so the database can enforce it (a counter row updated atomically, an exclusion constraint, a unique index). This is often the simplest.
Materialise the conflict: update a shared row so that two transactions write the same row and conflict.
Every SERIALIZABLE write path needs retry logic with a limit and jitter.
javascript
const { Client } = require('pg');
(async () => {
const a = new Client(), b = new Client();
await Promise.all([a.connect(), b.connect()]);
const reset = () => a.query(`DROP TABLE IF EXISTS bk31_doctors; CREATE TABLE bk31_doctors (name text PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO bk31_doctors VALUES ('alice', true), ('bob', true)`);
const onCall = async (c) => (await c.query('SELECT count(*)::int AS n FROM bk31_doctors WHERE on_call')).rows[0].n;
// Each doctor asks to go off call only when at least two are on call.
async function scenario(level) {
await reset();
await a.query(`BEGIN ISOLATION LEVEL ${level}`); await b.query(`BEGIN ISOLATION LEVEL ${level}`);
const [seenByA, seenByB] = [await onCall(a), await onCall(b)]; // both see 2
if (seenByA >= 2) await a.query("UPDATE bk31_doctors SET on_call = false WHERE name = 'alice'");
let outcome = 'both committed';
try {
if (seenByB >= 2) await b.query("UPDATE bk31_doctors SET on_call = false WHERE name = 'bob'");
await a.query('COMMIT');
await b.query('COMMIT');
} catch (err) {
outcome = `second transaction failed with ${err.code}`;
await a.query('COMMIT').catch(() => {}); await b.query('ROLLBACK');
}
return `${level.padEnd(16)} ${outcome}, on call afterwards: ${await onCall(a)}`;
}
console.log(await scenario('REPEATABLE READ'));
console.log(await scenario('SERIALIZABLE'));
// The retry sees the new state and refuses the change.
await b.query('BEGIN ISOLATION LEVEL SERIALIZABLE');
const nowOnCall = await onCall(b);
console.log('retry of the failed request: on call =', nowOnCall, '->', nowOnCall >= 2 ? 'allowed' : 'refused, one doctor must stay');
await b.query('ROLLBACK');
await a.query('DROP TABLE bk31_doctors');
await Promise.all([a.end(), b.end()]);
})();
Two connections are interleaved in a fixed order against the local PostgreSQL. The serializable failure can appear on the update or on the commit of the second transaction, and the script handles both places. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
REPEATABLE READ both committed, on call afterwards: 0
SERIALIZABLE second transaction failed with 40001, on call afterwards: 1
retry of the failed request: on call = 1 -> refused, one doctor must stay
Key points
Write skew is a rule broken by two transactions that update different rows.
Snapshot isolation does not detect it.
SERIALIZABLE aborts one transaction with 40001; retry it.
Alternatives: locks on the rule's rows, constraints, or a shared row.
Always add retry logic for serializable transactions.
Common mistakes
Assuming REPEATABLE READ is enough for multi-row rules.
Using SERIALIZABLE and not retrying 40001.
Long transactions that make serialization failures frequent.
Checking the rule in the application only, with no database support.
Retrying forever with no limit.
Follow-ups
How does PostgreSQL implement serializable snapshot isolation?
How would a unique or exclusion constraint prevent double booking?
What is a phantom, and how is it related to write skew?
Tips
Tell the on-call story.
State why snapshots miss it.
List four fixes.
32.backend-0032Hardsenior
What is a database deadlock, how does PostgreSQL detect and resolve it, and how do you prevent deadlocks in application code?
A deadlock is a cycle of transactions each waiting for a lock held by the next. PostgreSQL detects it after deadlock_timeout (one second by default), aborts one transaction with SQLSTATE 40P01 and lets the others continue. Prevent it by always taking locks in a consistent order (for example sort ids before updating), keeping transactions short, touching fewer rows, and retrying the aborted transaction.
Full answer
How it happens
Transaction 1 updates row A, then wants row B. Transaction 2 updated row B and now wants row A. Each waits for the other forever. The database cannot know which to cancel until it checks the wait graph.
Detection
A waiting session checks for cycles after deadlock_timeout. If it finds one, it aborts one transaction with ERROR 40P01 deadlock detected. The application must roll back (locks are released) and retry. Not every deadlock is a bug, but frequent ones are.
Prevention
Consistent order: any code that locks several rows or tables does it in the same order, for example ORDER BY id with SELECT ... FOR UPDATE, or sort the ids in the application. This removes cycles.
Short transactions: do slow work (network calls) outside the transaction. Lock late, commit early.
Lock fewer things: update in one statement, use the right indexes (a missing index makes updates lock and scan more rows), avoid unnecessary SELECT ... FOR UPDATE.
Use lock timeouts (lock_timeout) so waiting does not last forever.
Retry on 40P01 and 40001 with a limit and jitter.
Diagnosis: the log shows both statements and processes. pg_locks and pg_stat_activity show who waits for whom.
javascript
const { Client } = require('pg');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
const a = new Client(), b = new Client(), admin = new Client();
await Promise.all([a.connect(), b.connect(), admin.connect()]);
await a.query("SET deadlock_timeout = '100ms'"); // detect quickly in this demo
await admin.query(`DROP TABLE IF EXISTS bk32_rows; CREATE TABLE bk32_rows (id int PRIMARY KEY, n int); INSERT INTO bk32_rows VALUES (1, 0), (2, 0)`);
const touch = (c, id) => c.query('UPDATE bk32_rows SET n = n + 1 WHERE id = $1', [id]);
// Run a transaction that updates the rows in the given order, with a pause between the two updates.
async function work(c, ids) {
try {
await c.query('BEGIN');
await touch(c, ids[0]); await sleep(50); await touch(c, ids[1]);
await c.query('COMMIT');
return 'committed';
} catch (err) { await c.query('ROLLBACK'); return err.code; }
}
const clash = await Promise.all([work(a, [1, 2]), work(b, [2, 1])]); // opposite order
console.log('opposite lock order :', clash.slice().sort().join(' and '), '(one transaction was chosen as the victim)');
await admin.query('UPDATE bk32_rows SET n = 0');
const ordered = await Promise.all([work(a, [1, 2].sort()), work(b, [2, 1].sort())]); // same order for both
console.log('same lock order :', ordered.join(' and '));
console.log('counters afterwards :', (await admin.query('SELECT n FROM bk32_rows ORDER BY id')).rows.map((r) => r.n).join(', '));
await admin.query('DROP TABLE bk32_rows');
await Promise.all([a.end(), b.end(), admin.end()]);
})();
Two sessions update the same two rows in opposite order. deadlock_timeout is set to 100 ms for the demo (the default is one second). Which of the two transactions is chosen as the victim can vary, so the output is sorted. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
opposite lock order : 40P01 and committed (one transaction was chosen as the victim)
same lock order : committed and committed
counters afterwards : 2, 2
Key points
A deadlock is a cycle of lock waits.
PostgreSQL aborts one transaction with 40P01.
Take locks in a fixed order.
Keep transactions short and use lock timeouts.
Retry the aborted transaction.
Common mistakes
Locking rows in an order that depends on user input.
Long transactions that call external services.
Not retrying after a deadlock error.
Missing indexes that make updates lock too many rows.
Treating a deadlock as a database bug.
Follow-ups
How do you find the statements involved in a deadlock?
What is lock_timeout?
How do foreign keys create locks between tables?
Tips
Describe the cycle with two rows.
State consistent order as the main fix.
Mention retry.
33.backend-0033Mediummid
What is optimistic locking, how do you implement it with a version column in SQL, and when is it better than pessimistic locking?
Optimistic locking assumes conflicts are rare. You read the row together with a version number, and on update you add AND version = :old to the WHERE clause and increase the version. If another writer got there first, zero rows are updated and you know there was a conflict, so you reload and retry or tell the user. It avoids holding locks while users think, and works well for web forms and low contention data. Under heavy contention the retries cost more than waiting on a lock.
Full answer
The lost update
Two users load the same record. Both change it and save. The second save overwrites the first without knowing about it.
The pattern
Table has a version integer (or an updated_at timestamp, or a row hash).
Read: SELECT id, name, version FROM docs WHERE id = 1.
Update: UPDATE docs SET name = :new, version = version + 1 WHERE id = 1 AND version = :seen.
Check the affected row count. 1 means success. 0 means somebody changed the row: reload, merge or show a conflict message, and try again.
Notes
It also works over HTTP with ETag and If-Match, mapping a failure to 412 or 409.
No database locks are held between the read and the write, so there is no waiting and no deadlock.
For counters and simple increments, use an atomic UPDATE (balance = balance + 5) instead.
ORMs offer it as a built-in feature (a version column).
Choose pessimistic locking (SELECT FOR UPDATE) when conflicts are frequent, the work between read and write is short and inside one transaction, or retries would be expensive.
javascript
const { Client } = require('pg');
(async () => {
const db = new Client(); await db.connect();
await db.query(`DROP TABLE IF EXISTS bk33_docs; CREATE TABLE bk33_docs (id int PRIMARY KEY, body text NOT NULL, version int NOT NULL DEFAULT 1);
INSERT INTO bk33_docs VALUES (1, 'original', 1)`);
const load = async () => (await db.query('SELECT body, version FROM bk33_docs WHERE id = 1')).rows[0];
const save = async (body, seenVersion) => (await db.query('UPDATE bk33_docs SET body = $1, version = version + 1 WHERE id = 1 AND version = $2', [body, seenVersion])).rowCount;
// Both editors load version 1.
const editorA = await load(), editorB = await load();
console.log('editor A saves :', (await save('A edit', editorA.version)) === 1 ? 'saved' : 'conflict');
console.log('editor B saves :', (await save('B edit', editorB.version)) === 1 ? 'saved' : 'conflict (zero rows updated)');
console.log('row after both :', JSON.stringify(await load()));
// B reloads, applies the change again and retries.
const fresh = await load();
console.log('editor B retries :', (await save('A edit + B edit', fresh.version)) === 1 ? 'saved' : 'conflict');
console.log('final row :', JSON.stringify(await load()));
// Without the version check the second writer silently wins (a lost update).
await db.query("UPDATE bk33_docs SET body = 'original', version = 1");
await db.query("UPDATE bk33_docs SET body = 'A edit' WHERE id = 1");
await db.query("UPDATE bk33_docs SET body = 'B edit' WHERE id = 1");
console.log('no version check :', (await load()).body, '(A\'s change is gone)');
await db.query('DROP TABLE bk33_docs');
await db.end();
})();
Runs on the local PostgreSQL. The two editors are simulated by loading the same version twice, then saving one after the other. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
editor A saves : saved
editor B saves : conflict (zero rows updated)
row after both : {"body":"A edit","version":2}
editor B retries : saved
final row : {"body":"A edit + B edit","version":3}
no version check : B edit (A's change is gone)
Key points
Add a version to each row and check it in the update's WHERE clause.
Zero updated rows means a conflict.
No locks are held while users edit.
Retry or ask the user to resolve conflicts.
Use atomic updates for counters.
Common mistakes
Checking the version in the application instead of in the UPDATE.
Ignoring the row count of the update.
Using optimistic locking on a hot counter.
Not telling the user what changed.
Forgetting to include the version in every write path.
Follow-ups
How does an ORM implement a version column?
How would you do this over HTTP?
When do you prefer SELECT FOR UPDATE?
Tips
Show the WHERE version clause.
Say 'zero rows means conflict'.
Compare with pessimistic locking.
34.backend-0034Hardsenior
How does pessimistic locking work in SQL (SELECT FOR UPDATE, NOWAIT, SKIP LOCKED), and how do you use it to avoid lost updates and to build a job queue?
Pessimistic locking takes the lock before the work: SELECT ... FOR UPDATE locks the selected rows until the transaction ends, so other writers wait. This prevents lost updates in read-modify-write code. NOWAIT fails at once if a row is locked, and SKIP LOCKED skips locked rows, which lets several workers take different jobs from one table without blocking each other. Keep the transaction short, lock in a consistent order, and remember that locks cost throughput.
Full answer
Read-modify-write
Without a lock: two sessions read counter = 5, both write 6. One increment is lost. Putting the read and write in a transaction is not enough at READ COMMITTED.
With SELECT counter FROM t WHERE id = 1 FOR UPDATE, the second session waits until the first commits, then reads the new value. For simple increments the best fix is still one atomic UPDATE ... SET n = n + 1.
Lock modes and options
FOR UPDATE: exclusive lock for rows you will change. FOR SHARE: blocks writers, allows other readers that also share.
NOWAIT: raise error 55P03 instead of waiting. Good for interactive requests ("this item is being edited").
SKIP LOCKED: ignore locked rows. This turns a table into a work queue: each worker runs SELECT ... WHERE status = 'new' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1, processes, updates the status and commits.
Use lock_timeout to bound waiting.
Trade-offs
Pessimistic locks block other transactions and can deadlock. Keep the locked section small and in a fixed row order.
Never hold row locks while waiting for a user or a remote call. For long human edits use optimistic locking.
A queue in the database works for moderate rates. For high throughput use a broker.
javascript
const { Pool } = require('pg');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
const pool = new Pool({ max: 12 });
const clients = await Promise.all(Array.from({ length: 10 }, () => pool.connect()));
await clients[0].query(`DROP TABLE IF EXISTS bk34_counter; DROP TABLE IF EXISTS bk34_jobs;
CREATE TABLE bk34_counter (id int PRIMARY KEY, n int); INSERT INTO bk34_counter VALUES (1, 0);
CREATE TABLE bk34_jobs (id serial PRIMARY KEY, status text NOT NULL DEFAULT 'new'); INSERT INTO bk34_jobs (status) SELECT 'new' FROM generate_series(1, 5);`);
const counter = async () => (await clients[0].query('SELECT n FROM bk34_counter')).rows[0].n;
// Ten clients do read, wait a little, write n + 1.
async function increment(c, lock) {
await c.query('BEGIN');
const { rows } = await c.query(`SELECT n FROM bk34_counter WHERE id = 1 ${lock ? 'FOR UPDATE' : ''}`);
await sleep(30);
await c.query('UPDATE bk34_counter SET n = $1 WHERE id = 1', [rows[0].n + 1]);
await c.query('COMMIT');
}
await Promise.all(clients.map((c) => increment(c, false)));
console.log('10 increments, no lock : counter =', await counter(), '(updates were lost)');
await clients[0].query('UPDATE bk34_counter SET n = 0');
await Promise.all(clients.map((c) => increment(c, true)));
console.log('10 increments, FOR UPDATE : counter =', await counter());
// NOWAIT: fail fast when somebody holds the row.
await clients[0].query('BEGIN'); await clients[0].query('SELECT * FROM bk34_counter WHERE id = 1 FOR UPDATE');
const nowait = await clients[1].query('SELECT * FROM bk34_counter WHERE id = 1 FOR UPDATE NOWAIT').catch((e) => e.code);
console.log('NOWAIT on a locked row :', nowait);
await clients[0].query('ROLLBACK');
// SKIP LOCKED: five workers take five different jobs at the same time.
const taken = await Promise.all(clients.slice(0, 5).map(async (c) => {
await c.query('BEGIN');
const { rows } = await c.query("SELECT id FROM bk34_jobs WHERE status = 'new' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1");
await sleep(30); // the job is processed while the row is locked
await c.query("UPDATE bk34_jobs SET status = 'done' WHERE id = $1", [rows[0].id]);
await c.query('COMMIT');
return rows[0].id;
}));
console.log('SKIP LOCKED, 5 workers got :', taken.sort((x, y) => x - y).join(', '), '(each job once)');
await clients[0].query('DROP TABLE bk34_counter; DROP TABLE bk34_jobs');
clients.forEach((c) => c.release());
await pool.end();
})();
Ten pooled connections run at the same time against the local PostgreSQL. The sleeps force the overlap that causes the lost updates, so the result without a lock is below ten every time. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
10 increments, no lock : counter = 1 (updates were lost)
10 increments, FOR UPDATE : counter = 10
NOWAIT on a locked row : 55P03
SKIP LOCKED, 5 workers got : 1, 2, 3, 4, 5 (each job once)
Key points
FOR UPDATE locks rows until commit or rollback.
It prevents lost updates in read-modify-write code.
NOWAIT fails fast; SKIP LOCKED lets workers share a queue.
Keep locked sections short and in a fixed order.
Prefer an atomic UPDATE when it is enough.
Common mistakes
Holding FOR UPDATE locks during slow external calls.
Locking rows in different orders.
Using FOR UPDATE where an atomic UPDATE would do.
A polling queue table without SKIP LOCKED, so workers block each other.
Using database queues at rates where a broker is needed.
Follow-ups
What is the difference between FOR UPDATE and FOR NO KEY UPDATE?
How do advisory locks differ from row locks?
How do you stop a worker's job from being lost if it crashes?
Tips
Contrast with optimistic locking.
Name the three options.
Describe the job queue.
35.backend-0035Hardsenior
How do you build a distributed lock with Redis, and why are ownership checks, lock expiry and fencing tokens needed for correctness?
A Redis lock uses SET key token NX PX ttl: it sets the key only if absent, with an expiry (a lease) so a crashed owner cannot block everybody. Release must check that the token still belongs to you (a Lua compare-and-delete). But a lease can expire while the owner is paused (garbage collection, slow network), so two clients may both think they hold the lock. For correctness, protect the shared resource with a fencing token: an increasing number issued with each lock grant, which the resource checks and uses to reject writes from older holders.
Full answer
Basic lock
Acquire: SET lock:resource <random token> NX PX 30000. OK means you own it.
Release: run a Lua script that deletes the key only if its value equals your token. A plain DEL can remove a lock that was granted to someone else after yours expired.
Always use an expiry. Keep it longer than the work, and extend (renew) while working if needed.
Why it is not enough
Leases are time based. If a process pauses longer than the TTL (long GC pause, CPU starvation, a slow call), the lock expires, another client gets it, and the first process wakes up still believing it is the owner. Both write.
A single Redis node can fail over before the key replicates, which grants the lock twice. Redlock (several independent nodes) reduces but does not remove the timing problem.
Fencing tokens
The lock service gives each grant a number that only increases. The client sends it with every write. The resource (database, storage) remembers the highest token seen and rejects lower ones. So a delayed old holder cannot overwrite newer data. This needs the resource to cooperate.
Prefer alternatives when you can
A database row lock or unique constraint, a compare-and-set (optimistic) update, a single consumer per queue partition, or idempotent operations. Use a distributed lock for efficiency (avoid duplicate work) rather than for correctness unless you use fencing.
javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const RELEASE = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
async function acquire(owner, ttlMs) {
const token = await redis.incr('bk35:tokens'); // increasing number, used as the fencing token
const ok = await redis.set('bk35:lock', owner, 'PX', ttlMs, 'NX');
return ok ? { owner, token } : null;
}
// A storage that checks fencing tokens, and one that does not.
const storage = { value: null, highest: 0 };
const writeUnfenced = (v) => { storage.value = v; return true; };
const writeFenced = (v, token) => { if (token < storage.highest) return false; storage.highest = token; storage.value = v; return true; };
(async () => {
await redis.del('bk35:lock', 'bk35:tokens');
const A = await acquire('A', 100); // A gets the lock with a 100 ms lease...
await sleep(150); // ...then stalls (a long pause) past the lease
const B = await acquire('B', 1000); // the lock expired, so B gets it
console.log('A token:', A.token, '| B token:', B.token, '| B is the owner now:', (await redis.get('bk35:lock')) === 'B');
writeFenced('written by B', B.token);
console.log('A wakes up and writes, unfenced storage:', writeUnfenced('written by A (stale)'), '->', storage.value);
storage.value = 'written by B'; storage.highest = B.token;
console.log('A wakes up and writes, fenced storage :', writeFenced('written by A (stale)', A.token), '->', storage.value);
// Releasing a lock that is not yours.
console.log('A releases with a plain DEL :', await redis.del('bk35:lock'), '(B\'s lock is gone, though B still works)');
await redis.set('bk35:lock', 'B', 'PX', 1000, 'NX');
console.log('A releases with the token check :', await redis.eval(RELEASE, 1, 'bk35:lock', 'A'), '| B still holds it:', (await redis.get('bk35:lock')) === 'B');
await redis.del('bk35:lock', 'bk35:tokens');
redis.disconnect();
})();
A stall is simulated with a sleep longer than the lease. It runs on one local Redis node, so failover problems and Redlock are described in the text and were not tested. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
A token: 1 | B token: 2 | B is the owner now: true
A wakes up and writes, unfenced storage: true -> written by A (stale)
A wakes up and writes, fenced storage : false -> written by B
A releases with a plain DEL : 1 (B's lock is gone, though B still works)
A releases with the token check : 0 | B still holds it: true
Key points
SET NX PX gives a lease; the expiry prevents permanent blocking.
Release only when the stored token is yours (Lua).
A paused owner can lose the lock without knowing.
Fencing tokens let the resource reject stale writers.
Prefer database constraints or compare-and-set when possible.
Common mistakes
Releasing with DEL and no token check.
No expiry on the lock.
Assuming a lock guarantees mutual exclusion even when a process pauses.
Using a distributed lock where a database constraint would do.
Renewing leases from the same thread that may be blocked.
Follow-ups
What is Redlock and what are the criticisms of it?
How would a database implement the fencing check?
When is an advisory lock in PostgreSQL a better choice?
Tips
Cover acquire, release, expiry in order.
Explain the pause problem.
Say 'fencing tokens'.
36.backend-0036Mediummid
What is an idempotency key, and how do you implement it for a POST endpoint so that retries do not create duplicates?
An idempotency key is a unique value (a UUID) that the client sends with a POST request, for example in an Idempotency-Key header. The server stores the key with a hash of the request and the response. If the same key arrives again with the same request, the server returns the stored response without doing the work again. If the same key arrives with a different body, it answers 422. This makes retries after timeouts safe for payments, orders and other non-idempotent operations.
Full answer
Why it is needed
A client sends POST /payments and the connection times out. Did the server process it? The client cannot know. A blind retry may charge twice. The key makes the retry safe.
Implementation
Client generates a key per logical operation (one per payment attempt, reused for retries of it).
Server inserts a row (key, request hash, status) with a unique constraint on the key, in the same transaction as the business change.
If the insert succeeds, do the work, store the response (status and body) in the same row, commit, and respond.
If the key exists with the same request hash: return the stored response (many APIs add a replay header). If the stored response is not ready yet, the original request is still running: wait for it or answer 409.
If the key exists with a different request hash: answer 422 (the key was reused for something else).
Expire keys after a window (24 hours is common).
Details
Scope keys per user or API client.
Doing the key insert and the business change in one transaction removes the crash window where one exists without the other.
Safe by nature: GET, PUT and DELETE do not need keys. POST and PATCH may.
For calls to other systems, pass your own key on to them, such as a payment provider.
javascript
const { Client } = require('pg');
const crypto = require('node:crypto');
(async () => {
const db = new Client(); await db.connect();
await db.query(`DROP TABLE IF EXISTS bk36_idem; DROP TABLE IF EXISTS bk36_payments;
CREATE TABLE bk36_payments (id serial PRIMARY KEY, amount int NOT NULL);
CREATE TABLE bk36_idem (key text PRIMARY KEY, request_hash text NOT NULL, response jsonb)`);
async function createPayment(key, body) {
const hash = crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
await db.query('BEGIN');
const claimed = await db.query('INSERT INTO bk36_idem (key, request_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING key', [key, hash]);
if (claimed.rowCount === 1) { // first time we see this key: do the work
const { rows } = await db.query('INSERT INTO bk36_payments (amount) VALUES ($1) RETURNING id', [body.amount]);
const response = { status: 201, body: { id: rows[0].id, amount: body.amount } };
await db.query('UPDATE bk36_idem SET response = $2 WHERE key = $1', [key, response]);
await db.query('COMMIT');
return { ...response, replay: false };
}
const { rows } = await db.query('SELECT request_hash, response FROM bk36_idem WHERE key = $1', [key]);
await db.query('COMMIT');
if (rows[0].request_hash !== hash) return { status: 422, body: { error: 'idempotency key reused with a different request' } };
return { ...rows[0].response, replay: true };
}
const show = (label, r) => console.log(label.padEnd(30), r.status, JSON.stringify(r.body), r.replay === undefined ? '' : 'replay=' + r.replay);
show('first request, key k-1', await createPayment('k-1', { amount: 500 }));
show('retry after a timeout, k-1', await createPayment('k-1', { amount: 500 }));
show('same key, different amount', await createPayment('k-1', { amount: 900 }));
show('new key k-2', await createPayment('k-2', { amount: 500 }));
console.log('payments stored (not 4):', (await db.query('SELECT count(*)::int AS n FROM bk36_payments')).rows[0].n);
await db.query('DROP TABLE bk36_idem; DROP TABLE bk36_payments');
await db.end();
})();
Runs on the local PostgreSQL. The key claim and the payment are in one transaction. Concurrent requests with the same key are covered in the next item. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
first request, key k-1 201 {"id":1,"amount":500} replay=false
retry after a timeout, k-1 201 {"id":1,"amount":500} replay=true
same key, different amount 422 {"error":"idempotency key reused with a different request"}
new key k-2 201 {"id":2,"amount":500} replay=false
payments stored (not 4): 2
Key points
The client sends a unique key and reuses it when retrying.
The server stores key, request hash and response.
Same key and same request: return the stored response.
Same key and different request: 422.
Store the key in the same transaction as the work.
Common mistakes
Generating a new key on every retry.
Storing the key outside the transaction of the work.
Not comparing the request body with the stored one.
Letting keys live forever.
Using the key for a different user's request (no scoping).
Follow-ups
How long should keys be kept?
What does Stripe return for a replayed request?
How do you make a webhook consumer idempotent?
Tips
Open with the timeout problem.
Walk through insert, work, store, replay.
Mention 422 for mismatches.
37.backend-0037Hardsenior
What happens when two requests with the same idempotency key arrive at the same time, and how do you guarantee that the work runs only once?
A unique constraint on the idempotency key makes the database the referee. Both requests try to insert the key inside their transaction. The first one gets the row. The second one blocks on the unique index until the first commits (then it sees a conflict and returns the stored response) or rolls back (then it can claim the key and do the work). The work and the key are in the same transaction, so a crash leaves nothing behind. Outside a database transaction (for example when the work calls an external API) you need a status column (in progress, done) and a 409 or retry-later answer for requests that arrive while the first is running.
Full answer
Races to cover
Two simultaneous requests, same key: without a unique constraint both pass a "does the key exist?" check and both run. Always claim the key with an atomic INSERT (or SET NX in Redis), never check then insert.
Crash after claiming the key but before finishing: if the claim and the work are in one transaction, the claim vanishes with the rollback, and a retry starts clean. If they are separate (external side effects), store a status and an expiry, and let a janitor or the next retry take over stale in-progress records. Pass the same key to the external system so the external call is idempotent as well.
Failure of the work: store the error response too if it is final (a validation error), but not for transient failures that the client should retry.
Same key, different body: 422.
Choosing the waiting behaviour
Block until the first finishes (simple, uses a database lock for the wait, holds a connection).
Return 409 with Retry-After so the client retries (cheaper under load).
What exactly-once means here: at-least-once requests plus an idempotent server give exactly one effect for one key within the retention window.
javascript
const { Pool } = require('pg');
const crypto = require('node:crypto');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
const pool = new Pool({ max: 8 });
await pool.query(`DROP TABLE IF EXISTS bk37_idem; DROP TABLE IF EXISTS bk37_orders;
CREATE TABLE bk37_orders (id serial PRIMARY KEY, item text NOT NULL);
CREATE TABLE bk37_idem (key text PRIMARY KEY, response jsonb)`);
async function createOrder(key, item, { crash = false } = {}) {
const c = await pool.connect();
try {
await c.query('BEGIN');
const claimed = await c.query('INSERT INTO bk37_idem (key) VALUES ($1) ON CONFLICT DO NOTHING RETURNING key', [key]); // waits if another transaction holds this key
if (claimed.rowCount === 0) {
const { rows } = await c.query('SELECT response FROM bk37_idem WHERE key = $1', [key]);
await c.query('COMMIT');
return { ...rows[0].response, replay: true };
}
await sleep(50); // the work takes a while
const { rows } = await c.query('INSERT INTO bk37_orders (item) VALUES ($1) RETURNING id', [item]);
if (crash) throw new Error('process crashed before commit');
const response = { status: 201, orderId: rows[0].id };
await c.query('UPDATE bk37_idem SET response = $2 WHERE key = $1', [key, response]);
await c.query('COMMIT');
return { ...response, replay: false };
} catch (err) { await c.query('ROLLBACK'); return { status: 500, error: err.message }; }
finally { c.release(); }
}
// 1. Five identical requests at the same moment.
const results = await Promise.all(Array.from({ length: 5 }, () => createOrder('key-A', 'book')));
const orders = (await pool.query('SELECT count(*)::int AS n FROM bk37_orders')).rows[0].n;
console.log('5 concurrent requests, same key:', results.filter((r) => !r.replay).length, 'did the work,', results.filter((r) => r.replay).length, 'replayed | orders created:', orders);
console.log('all five got the same order id :', new Set(results.map((r) => r.orderId)).size === 1);
// 2. The first request crashes. Nothing is left behind, and the retry works.
const crashed = await createOrder('key-B', 'pen', { crash: true });
const afterCrash = (await pool.query("SELECT count(*)::int AS n FROM bk37_idem WHERE key = 'key-B'")).rows[0].n;
const retry = await createOrder('key-B', 'pen');
console.log('crash, then retry :', crashed.status, '-> key rows after crash:', afterCrash, '-> retry:', retry.status, 'replay =', retry.replay);
await pool.query('DROP TABLE bk37_idem; DROP TABLE bk37_orders');
await pool.end();
})();
Five requests share one key and run on separate pooled connections. The work includes a 50 ms pause so that the requests really overlap, and the crash is simulated with a thrown error before COMMIT. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
5 concurrent requests, same key: 1 did the work, 4 replayed | orders created: 1
all five got the same order id : true
crash, then retry : 500 -> key rows after crash: 0 -> retry: 201 replay = false
Key points
Claim the key with one atomic insert, never check then insert.
The unique index makes concurrent duplicates wait or conflict.
Keep claim and work in one transaction when possible.
For external side effects, use an in-progress status and expiry.
Pass the key on to downstream systems.
Common mistakes
Checking for the key with SELECT and then inserting.
Claiming the key in one transaction and doing the work in another, with no status.
Waiting forever on an in-flight key (no timeout).
Caching transient failures as final results.
Forgetting idempotency for the downstream call.
Follow-ups
How would you do this with Redis SET NX instead of a database?
What do you return to a request that arrives while the first is still running?
How do stale in-progress records get cleaned up?
Tips
Name the race first.
Say 'one atomic claim'.
Describe the crash case.
38.backend-0038Easyfresher
How do fixed window and sliding window rate limiters work, and what is the burst problem at window boundaries?
A fixed window counter counts requests in calendar slots (for example per minute) and rejects above the limit. It is cheap, but a client can send the full limit at the end of one window and again at the start of the next, doubling the rate for a short time. A sliding window looks at the last N seconds from now: the sliding log stores every timestamp (exact, more memory), and the sliding window counter blends the current and previous window counts (small memory, close approximation).
Full answer
Fixed window counter
Key = client + floor(now / window). Increment, compare with the limit. Memory: one number per client. Weakness: the boundary burst. With a limit of 5 per 10 seconds, 5 requests at second 9.9 and 5 more at second 10.1 are all allowed (10 requests in 0.2 seconds).
Sliding window log
Keep the timestamp of every accepted request. On a new request drop timestamps older than the window, count the rest, allow if below the limit. Exact, but memory grows with the limit (O(limit) per client).
Sliding window counter
Keep counts for the current and previous windows. Estimated count = previous * (fraction of the previous window still inside the sliding window) + current. Constant memory, small error, and very popular.
Other points
Choose the key: user, API key, IP address (careful with shared NATs), or a combination.
Return 429 with Retry-After and rate limit headers. Do the limiting early, before expensive work.
Use a shared store (Redis) when you have several servers, and make the check atomic.
javascript
const LIMIT = 5, WINDOW = 10; // 5 requests per 10 seconds
function fixedWindow() {
const counts = new Map();
return (now) => { const slot = Math.floor(now / WINDOW); const n = (counts.get(slot) ?? 0) + 1; counts.set(slot, n); return n <= LIMIT; };
}
function slidingLog() {
let log = [];
return (now) => { log = log.filter((t) => t > now - WINDOW); if (log.length >= LIMIT) return false; log.push(now); return true; };
}
function slidingCounter() {
const counts = new Map();
return (now) => {
const slot = Math.floor(now / WINDOW), elapsed = (now % WINDOW) / WINDOW;
const estimate = (counts.get(slot - 1) ?? 0) * (1 - elapsed) + (counts.get(slot) ?? 0);
if (estimate + 1 > LIMIT) return false;
counts.set(slot, (counts.get(slot) ?? 0) + 1);
return true;
};
}
// Five requests just before the boundary at t = 10 s, five more just after it.
const times = [9.5, 9.6, 9.7, 9.8, 9.9, 10.1, 10.2, 10.3, 10.4, 10.5];
for (const [name, make] of [['fixed window', fixedWindow], ['sliding log', slidingLog], ['sliding counter', slidingCounter]]) {
const allow = make();
const result = times.map((t) => allow(t));
console.log(name.padEnd(16), result.map((r) => (r ? 'ok ' : 'no ')).join(''), '| allowed in 1 second:', result.filter(Boolean).length);
}
console.log('limit is', LIMIT, 'per', WINDOW, 'seconds, so at most', LIMIT, 'should pass in these 1.0 seconds');
Plain functions with explicit timestamps, so the result is exact and repeatable. Real systems read the clock and keep the state in Redis or a gateway. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
fixed window ok ok ok ok ok ok ok ok ok ok | allowed in 1 second: 10
sliding log ok ok ok ok ok no no no no no | allowed in 1 second: 5
sliding counter ok ok ok ok ok no no no no no | allowed in 1 second: 5
limit is 5 per 10 seconds, so at most 5 should pass in these 1.0 seconds
Key points
Fixed windows are simple and allow double bursts at the boundary.
A sliding log is exact but stores every timestamp.
A sliding window counter approximates with two numbers.
Return 429 with Retry-After.
Use a shared, atomic store for many servers.
Common mistakes
Using a fixed window and being surprised by double bursts.
Limiting only by IP address behind a shared proxy.
Keeping unlimited counters in memory for every client.
Limiting after the expensive work is done.
Not returning Retry-After.
Follow-ups
How does a sliding window counter estimate the count?
Where do you apply rate limits (gateway, application, both)?
How do you limit by user and by IP together?
Tips
Describe the boundary burst with numbers.
Compare memory use.
Say that 429 and Retry-After are part of the contract.
39.backend-0039Mediummid
How do the token bucket and leaky bucket algorithms differ, and which one allows bursts?
A token bucket holds up to capacity tokens and refills at a steady rate. Each request takes a token, so a client can burst up to the capacity and then is limited to the refill rate. A leaky bucket (as a queue) accepts requests into a bucket of fixed size and processes them at a constant rate. It smooths output, never bursts, and drops what does not fit. Use a token bucket to allow controlled bursts (most APIs) and a leaky bucket to shape traffic to a steady rate for a downstream system.
Full answer
Token bucket
State: tokens (a number) and the last refill time. On a request: add elapsed * rate tokens (up to capacity), then if tokens >= 1 take one and allow, else reject and tell the client how long until the next token (Retry-After = (1 - tokens) / rate).
Burst size = capacity, long-term rate = refill rate. Needs only two numbers per client, and no timers (refill lazily).
Leaky bucket
Requests enter a queue (the bucket) that has a maximum size. The queue is drained at a constant rate. If the queue is full, new requests are dropped. A variant uses the bucket as a meter and does not queue at all.
Output is smooth, which protects a fragile downstream. Added latency for queued requests is the cost.
Choosing
Public APIs: token bucket (burst friendly, simple).
Calls to a downstream system with a hard rate limit: leaky bucket or a queue with a fixed consumer rate.
Often both: a token bucket at the edge and a queue in front of a slow dependency.
javascript
class TokenBucket {
constructor(capacity, refillPerSecond) { this.capacity = capacity; this.rate = refillPerSecond; this.tokens = capacity; this.last = 0; }
take(now) {
this.tokens = Math.min(this.capacity, this.tokens + (now - this.last) * this.rate); this.last = now;
if (this.tokens >= 1) { this.tokens -= 1; return { allowed: true }; }
return { allowed: false, retryAfter: Math.ceil((1 - this.tokens) / this.rate) };
}
}
class LeakyBucket { // a queue that is drained at a constant rate
constructor(size, leakPerSecond) { this.size = size; this.interval = 1 / leakPerSecond; this.nextFree = 0; this.queued = []; }
add(now) {
this.queued = this.queued.filter((t) => t > now); // requests already processed leave the bucket
if (this.queued.length >= this.size) return { accepted: false };
const processAt = Math.max(now, this.nextFree) + this.interval;
this.nextFree = processAt; this.queued.push(processAt);
return { accepted: true, processAt };
}
}
// 8 requests arrive at t = 0 s, then 3 more at t = 4 s. Capacity 5, rate 1 per second.
const bucket = new TokenBucket(5, 1), leaky = new LeakyBucket(5, 1);
const arrivals = [0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4];
console.log('arrival token bucket leaky bucket (processed at)');
for (const t of arrivals) {
const a = bucket.take(t), b = leaky.add(t);
console.log(`t=${t}s `, (a.allowed ? 'allowed now' : `rejected, retry in ${a.retryAfter}s`).padEnd(28), b.accepted ? `t=${b.processAt}s` : 'dropped');
}
Both limiters get explicit timestamps, so the timeline is exact. The leaky bucket here queues requests and shows when each one is processed. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
arrival token bucket leaky bucket (processed at)
t=0s allowed now t=1s
t=0s allowed now t=2s
t=0s allowed now t=3s
t=0s allowed now t=4s
t=0s allowed now t=5s
t=0s rejected, retry in 1s dropped
t=0s rejected, retry in 1s dropped
t=0s rejected, retry in 1s dropped
t=4s allowed now t=6s
t=4s allowed now t=7s
t=4s allowed now t=8s
Key points
Token bucket: burst up to capacity, then the refill rate.
Retry-After comes from the missing token fraction.
Pick by whether bursts are acceptable.
Common mistakes
Mixing up which algorithm allows bursts.
Refilling with a background timer for every client.
Using floating point tokens without clamping to the capacity.
Not returning Retry-After.
Using one global bucket for all clients.
Follow-ups
How would you implement a token bucket in Redis atomically?
How do you set capacity and refill rate for a paid plan?
What is GCRA?
Tips
Say burst versus smooth.
Give the refill formula.
Name a use case for each.
40.backend-0040Hardsenior
How do you implement a rate limiter shared by many servers with Redis, why must the check be atomic, and should the limiter fail open or fail closed?
Keep the limiter state in Redis so all servers share it. A sliding window log fits a sorted set: remove entries older than the window, count the rest, add the new request if under the limit. The three steps must be atomic, or concurrent requests all pass the check before any is recorded and the limit is exceeded. A Lua script (or a transaction with the right guards) runs them as one unit. Decide what happens when Redis is down: fail open (allow) for availability, or fail closed (reject) for protection.
Full answer
Design
Key per client: rl:{api_key}. Sorted set: score = timestamp in milliseconds, member = unique request id.
Script (one atomic call): ZREMRANGEBYSCORE key 0 (now - window); count = ZCARD key; if count < limit then ZADD key now member, PEXPIRE key window, return allowed and remaining; else return denied and the time until the oldest entry leaves the window.
Use the Redis server clock (TIME command in the script) so that application servers with clock drift do not disagree.
Set an expiry so idle clients do not stay in memory. Memory is O(limit) per client. For very high limits use the counter or token bucket variants.
Why atomic
Separate commands (count, then add) let 20 concurrent requests all read count 4 with a limit of 5, and all add. A MULTI/EXEC block does not help for read-then-decide logic, because the decision happens in the client. Lua scripts execute without interleaving.
Operational choices
Fail open or closed? A limiter outage that blocks all traffic is often worse than the abuse it prevents, so many APIs fail open and alert. Fail closed for security sensitive limits (login, password reset).
Add a short local timeout to Redis calls so the limiter cannot slow the API.
Return 429, Retry-After and RateLimit headers. Shard keys in Redis Cluster by client.
Runs on the local Redis server. Twenty requests start at once against a limit of five, once with a racy check and once with the Lua script. The outage is simulated with a connection to a closed port. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
limit 5, 20 concurrent requests -> racy check allowed more than 5: true | atomic script allowed: 5
key expires on its own : true
Redis down, fail open : true | fail closed: false
Key points
Share limiter state through Redis.
Run remove, count and add as one atomic Lua script.
A check-then-add race lets bursts through the limit.
Use the Redis clock and key expiry.
Decide fail open or fail closed per use case.
Common mistakes
Counting and adding in separate commands.
Using each app server's own clock.
No key expiry.
Failing closed for every endpoint and turning a Redis outage into a full outage.
Using a sorted set for very high limits where a counter is enough.
Follow-ups
How would you implement a token bucket in a Lua script?