Quiz · Hard
Sixteen harder scenario questions: race conditions, sharding, replication lag, cache stampedes, idempotency, sagas, deadlocks, JWT revocation and zero-downtime migrations.
Two users try to book the last seat at the same moment. Your code does SELECT to check the seat is free and then INSERTs a booking. Which fix is race-proof?
Check twice in application code
Cache the seat status for one second
Add a UNIQUE constraint on (seat_id, event_id) or lock the row with SELECT ... FOR UPDATE inside a transaction
Disable the booking button in the browser
Check-then-insert has a race window where both transactions see the seat as free. Only the database can arbitrate: a unique constraint rejects the second insert, and a row lock serializes the two. Application-level checks, caching and UI tricks cannot close the window.
Your app shards users by country. 70% of users are in one country. What is the main problem?
A hot shard: that one node gets most of the load while others sit idle
Joins become impossible
Transactions stop working in each shard
The shard key must be numeric
A good shard key spreads load and data evenly. A skewed key creates a hot spot that limits the throughput of the whole system. Hashing a high-cardinality key such as user_id distributes better (at the cost of range queries).
A JWT access token cannot be revoked once issued. Which design best limits the damage of a stolen token?
Make tokens valid for a year
Store the token in the URL
Sign tokens with a shorter secret
Short-lived access tokens (minutes) plus a revocable refresh token stored server-side
Short expiry bounds the window of abuse; the refresh token can be checked and revoked on the server. Long lifetimes, tokens in URLs (leak via logs and referrers) and weaker secrets all make things worse.
A mobile app retries POST /payments after a network timeout and the customer is charged twice. What prevents this?
Switching the endpoint to GET
An idempotency key sent by the client and remembered by the server so a repeated request returns the original result
Increasing the timeout to one hour
Using HTTP/2
The client sends a unique key per logical operation; the server stores the result under that key and returns it for retries instead of charging again. GET must not change state, and longer timeouts do not remove the ambiguity of a lost response.
A very popular cache key expires and thousands of requests hit the database at the same instant. What is this called and what mitigates it?
Phantom read; use serializable isolation
Cache stampede; use request coalescing/locking and jittered TTLs
N+1; use a join
Deadlock; reorder updates
A cache stampede (thundering herd) happens when many requests miss at once and all rebuild the value. Let one request rebuild while others wait or serve slightly stale data, and add random jitter so keys do not expire together.
After a user saves their profile, the next page load (served from a read replica) still shows the old data. What is the most likely cause and a common fix?
The ORM is broken; replace it
HTTPS caching; disable TLS
Normalization; denormalize the table
Replication lag; read from the primary for a short time after a write (read-your-writes)
Replicas apply changes asynchronously, so they can lag behind the primary. Route reads that must see the user's own writes to the primary, or wait until the replica has caught up.
A table has a composite index on (country, city). Which query can use it efficiently?
WHERE country = 'FR' and city = 'Paris'
WHERE city = 'Paris'
WHERE city LIKE '%ris'
WHERE city LIKE 'Par%' with no condition on country
A composite B-tree index is sorted by the first column, then the second (leftmost-prefix rule). A filter that includes the leading column can seek into it; a filter on city alone cannot, and a leading wildcard cannot use it either.
An order spans three microservices (orders, payments, inventory), each with its own database. How do you keep them consistent without a distributed ACID transaction?
Use one giant lock across all services
Disable retries
A saga: a sequence of local transactions with compensating actions (e.g. refund) if a later step fails
Share a single connection string
Cross-service ACID transactions are impractical. A saga coordinates local transactions and undoes completed steps with compensating transactions when something fails, giving eventual consistency.
Two transactions deadlock: T1 updates row A then B, T2 updates row B then A. What is the most effective prevention?
Raise the connection pool size
Disable foreign keys
Use UUIDs
Always update rows in the same order in every transaction
A deadlock needs a cycle of waits. If everyone locks resources in a consistent global order, a cycle cannot form. Keeping transactions short helps too; pool size, FK settings and id types are irrelevant.
You rename a database column in one release and deploy new code. During the rolling deploy, old instances start failing. What approach avoids this?
Rename first, deploy later
Expand and contract: add the new column, deploy code that handles both, migrate data, then drop the old column
Stop the whole site during deploys
Disable logging during the migration
During a rolling deploy old and new code run at the same time, so the schema must work for both. Expand/contract keeps each step backward compatible.
A team says: 'Our API is safe from other websites because we configured CORS to allow only our domain.' What is wrong with this reasoning?
CORS only works over HTTP/1.1
CORS encrypts data in transit
CORS is enforced by browsers; curl, scripts and other servers ignore it, so it does not replace authentication and authorization
CORS is only for cookies
CORS is a browser policy that decides whether front-end JavaScript may read a cross-origin response. Any non-browser client can still call the API, so real protection requires auth, authorization and rate limiting.
Why is SHA-256(salt + password) still a poor choice for password storage?
It is too fast, so attackers with GPUs can test billions of guesses per second; use a deliberately slow function like Argon2id or bcrypt
SHA-256 is reversible
Salts make hashes longer than the database allows
SHA-256 cannot be used on the server
Salting prevents rainbow tables but not brute force against a single hash. General-purpose hashes are designed to be fast; password hashes have a tunable cost (and memory hardness) to slow guessing. SHA-256 is one-way, not reversible.
A Node.js API handles thousands of simple requests fine, but a single endpoint that resizes large images makes every other request slow. Why?
The CPU-heavy work blocks the single-threaded event loop
Node cannot run more than 10 requests
HTTP is stateless
The database connection pool is full
Node's event loop runs JavaScript on one thread, so a long synchronous computation delays everything else. Move it to worker threads or a job queue, or use a separate service.
A message queue guarantees at-least-once delivery. What must your consumers be?
Written in the same language as the producer
Synchronous
Idempotent, because the same message may be delivered more than once
Stateless HTTP servers
At-least-once means retries can produce duplicates (for example if an ack is lost). Processing a duplicate must not create a second charge, email or row, so the handler has to be idempotent.
Many serverless function instances each open their own database connections, and PostgreSQL starts refusing connections. What is the standard fix?
Increase the isolation level
Put a connection pooler (e.g. PgBouncer or a managed pooler) between the functions and the database
Use UUIDs as keys
Add an index
Databases handle a limited number of connections, each costing memory. A pooler multiplexes many client connections onto a small number of real ones.
An optimistic locking update looks like UPDATE docs SET body = ?, version = version + 1 WHERE id = ? AND version = ?. What does it mean when it affects 0 rows?
The query succeeded silently
The database crashed
The index was missing
The document does not exist anymore or someone else updated it first, so you must reload and retry or report a conflict
The version check fails if another writer already incremented the version. This detects lost updates without holding locks, at the cost of handling retries or conflicts in the application.