Rate limiting a database: protect it before it falls over
Connection caps, queueing, per-tenant budgets and back pressure keep one noisy client from taking everyone down.
More on Running a database in production
Keep learning
Overview
Requests per caller per second Token / leaky bucket, 429 Connection pool Statements in flight per app instance Pool max size, borrow timeout Proxy / pooler By user, database or query pattern Queueing and routing rules Database account Connections for one login Per-account connection cap Total connections, time per statement Connection cap, statement timeout, lock timeout CPU share of a class of work Workload priority class Server connection cap A hard wall before memory runs out Per-account cap One service cannot take every slot That service fails first Pool size per app Back pressure in the app, not the DB Callers wait in the app Statement timeout One bad query has a bounded cost Long reports must run elsewhere Lock wait timeout Hidden queues behind locks are bounded Errors the app must retry Idle connection timeout Leaked connections come back Reconnect cost for idle clients chapters · running a database in production Rate limiting a database: protect it before it falls over A database finishes a fixed amount of work per second. Past that, queues grow and everyone is late. Rate limiting decides in advance who gets served and what happens to the rest.
1. Why overload makes everything worse
Feedback loop: more requests in flight cause more contention, which makes each query slower, which by Little's law puts even more requests in flight. In flight ↑ Contention ↑ locks, CPU, cache churn Each query slower same arrival rate λ, longer W → more in flight
2. Token bucket and leaky bucket
Token bucket: quiet time stores tokens, so short bursts pass. Leaky bucket: a queue that drains at a fixed rate, smooth output but queued requests wait. Size the burst to what the database absorbs at once, a second or two of capacity. Key buckets by tenant, API key or query class so a heavy caller drains only its own.
3. Layers: where to limit
knows who and why ↓ the last slot Use several layers, outermost first. Limits from the caller down to the server What it limits Knob (generic)
4. Admission control, back pressure, graceful degradation
Admission control decides at the door, before work starts. Back pressure pushes the limit upstream: a full pool makes callers wait, a 429 makes clients slow down. Serve slightly stale data from a cache. Drop optional features (recommendations, counts). Delay background jobs. Reject low-priority work with 429 + Retry-After. Keep login and checkout alive last. Clients must retry with exponential back-off and jitter, or a limit becomes a storm.
5. Choose limits from measured capacity
Load-test with rising concurrency: throughput climbs, then flattens at the knee. Plan for 70 to 80% of it and re-measure after schema, index or hardware changes. Knobs (generic) and what they trade Watch queries running, not connections open (mostly idle). Running climbing while throughput is flat means you are past the knee. Related: rate limiter interview, latency vs throughput. ⚙ In real engines MySQL: max_connections, MAX_USER_CONNECTIONS, max_execution_time, resource groups, ProxySQL (MySQL settings). PostgreSQL: max_connections, role CONNECTION LIMIT, statement_timeout, lock_timeout, PgBouncer (PostgreSQL settings). Running vs connected: MySQL diagnostics, PostgreSQL locks.
Recap
Limit at several layers: caller, pool, proxy, account, server, scheduler. Fail early and clearly, degrade by priority, make clients back off with jitter. Set limits from the measured knee, about 70 to 80% of it.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.