Most launch-day outages aren't dramatic. They're four small things nobody got round to: a missing index, an unbounded connection count, a write that isn't safe to repeat, and no limit on how often one client can call the API.
Here is a short checklist, with code, for a Node.js and PostgreSQL backend. Treat the snippets as patterns to adapt, not a drop-in implementation.
1. Index the query you actually run
Start with the query your busiest endpoint uses, and ask the database how it executes it.
EXPLAIN ANALYZE
SELECT *
FROM bookings
WHERE sitter_id = $1
AND starts_at >= now()
ORDER BY starts_at
LIMIT 50;
If you see a sequential scan over a large table, add an index that matches the filter and the sort:
CREATE INDEX CONCURRENTLY idx_bookings_sitter_start
ON bookings (sitter_id, starts_at);
CONCURRENTLY builds the index without blocking writes (it can't run inside a transaction block). Run EXPLAIN ANALYZE again to confirm the plan changed, and don't add indexes you can't justify, since each one slows writes.
2. Pool your database connections
Every PostgreSQL connection costs memory on the server, so opening one per request will exhaust the database under load. Use a pool with a sensible cap:
import pg from 'pg';
export const pool = new pg.Pool({
max: 10, // keep well below the database's connection limit
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 2_000, // fail fast instead of queueing forever
});
Use pool.query() for single statements. When you check out a client for a transaction, always release it in a finally block, or the pool will quietly run dry.
3. Make writes idempotent
Clients retry. Networks drop responses. If a repeated request creates a second booking or a second charge, you have a bug that only appears under stress.
Ask clients to send an Idempotency-Key header, and store it with a unique constraint:
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
app.post('/bookings', async (req, res, next) => {
const key = req.get('Idempotency-Key');
if (!key) return res.status(400).json({ error: 'Idempotency-Key header required' });
const client = await pool.connect();
try {
await client.query('BEGIN');
const claimed = await client.query(
'INSERT INTO idempotency_keys (key) VALUES ($1) ON CONFLICT DO NOTHING RETURNING key',
[key]
);
if (claimed.rowCount === 0) {
await client.query('ROLLBACK');
const prev = await pool.query('SELECT response FROM idempotency_keys WHERE key = $1', [key]);
return res.status(200).json(prev.rows[0]?.response ?? { status: 'processing' });
}
const booking = await createBooking(client, req.body); // your business logic
await client.query('UPDATE idempotency_keys SET response = $2 WHERE key = $1', [
key,
JSON.stringify(booking),
]);
await client.query('COMMIT');
res.status(201).json(booking);
} catch (err) {
await client.query('ROLLBACK');
next(err);
} finally {
client.release();
}
});
Claiming the key and doing the work in one transaction means a crash can't leave a key marked as used when the booking was never created. Delete old keys on a schedule, and decide how long a key stays valid.
4. Rate limit the API
One client stuck in a retry loop shouldn't be able to degrade the service for everyone.
import rateLimit from 'express-rate-limit';
app.use(
'/api/',
rateLimit({
windowMs: 60_000, // one minute
limit: 100, // requests per window per client (older versions call this `max`)
standardHeaders: true,
legacyHeaders: false,
})
);
The default in-memory store works for a single process. If you run several instances, use a shared store such as Redis so the limit applies across all of them. Return clear 429 responses and document the limits.
Bonus: health check and graceful shutdown
A load balancer needs to know whether an instance is alive, and a deployment shouldn't cut off requests in flight:
app.get('/healthz', async (_req, res) => {
try {
await pool.query('SELECT 1');
res.json({ ok: true });
} catch {
res.status(503).json({ ok: false });
}
});
const server = app.listen(3000);
process.on('SIGTERM', () => {
server.close(async () => { // stop accepting new requests, finish current ones
await pool.end();
process.exit(0);
});
});
Pre-launch checklist
- The slowest endpoint's query has been checked with
EXPLAIN ANALYZE - Connection pool size is capped and clients are always released
- Money-moving and booking-style writes are idempotent
- Rate limits are in place, and shared across instances
- Health check and graceful shutdown work
- Logs, metrics and alerts show errors before users do
- A backup has been restored at least once
- A load test has run against expected launch traffic
Wrapping up
None of these changes is clever. They're the unglamorous basics that keep a backend steady when real traffic arrives. Add them early, test them on purpose, and your launch day gets a lot quieter.
Written by the team at Clickmasters, a remote-first software development company. We offer backend development and cloud and DevOps for web, mobile and SaaS products.
Top comments (0)