How should a Docker Compose API recover from database outages without restart loops or duplicate writes? #214324
Replies: 4 comments
This comment was marked as off-topic.
This comment was marked as off-topic.
|
Building on what @asxxb covered, here's the concrete way to wire this up in Node.js and Express with MySQL, MongoDB, and Redis running on Docker Compose. Things shift a bit when you scale out to multiple instances. Reconnecting versus terminating calls for a specific approach. You'll almost always want to keep the Node process alive and let the drivers handle reconnection. Reserve process.exit(1) only for poisoned process state situations. Think unhandled promise rejections, exhausted file descriptors, or a deadlocked pool. Keeping /health/live returning 200 while /health/ready flips to 503 prevents Docker from restarting the container endlessly. It still signals that traffic can't be served. To stop reconnect storms and memory buildup when there's an outage, don't write custom retry loops around individual queries. Use your database drivers' built-in pooling and fail-fast settings instead. In mysql2, keep connectionLimit low per container. Set a strict queueLimit (say, 50) with a 5-second connectTimeout. Excess requests reject immediately with 503 rather than piling up in RAM. For ioredis, set enableOfflineQueue to false and maxRetriesPerRequest to 1. Use a retryStrategy with exponential backoff plus random jitter. This spreads reconnections out naturally. MongoDB or Mongoose? Drop serverSelectionTimeoutMS from 30 seconds down to around 5000ms. This prevents readiness checks and writes from hanging the event loop during failover. Redis outages need a different tactic. Separate hard dependencies from soft ones. Your /health/ready check should only verify critical datastores your core API needs to function, like MySQL and MongoDB. Wrap Redis calls in try/catch or a lightweight circuit breaker. If redis.status isn't ready, your endpoints bypass the cache gracefully and query MySQL directly instead. You can expose /health/deps returning 200 with JSON breakdowns of each service's status. Monitor without taking the entire API down. When a socket drops mid-commit (ECONNRESET scenarios), the API can't know if MySQL actually committed before the connection broke. Never blindly retry a raw write. Require clients to send an Idempotency-Key header on POST and PATCH requests (UUID format works well). Store that key in a dedicated idempotency table with a UNIQUE constraint inside the same database transaction as your business write. Connection drops? Return 503 with a Retry-After header. When the client retries safely using the same key, your handler hits the unique constraint or returns the stored response. No duplicate rows get created. Testing this locally in Docker Compose doesn't require external chaos tools. Simulate a frozen database or TCP blackhole by running docker compose pause mysql. Verify /health/ready switches to 503 within your timeout. Then run docker compose unpause mysql and watch recovery happen. Use docker network disconnect to test abrupt socket drops versus clean stops. Run a load generator like autocannon against write endpoints while executing docker compose stop -t 15 api. Confirm in-flight requests drain cleanly with 200s before exit. Scaling from single-host to multiple API instances changes several trade-offs. On one host, a single pool can safely claim most of MySQL's max_connections. With multiple replicas you divide that connection budget across every container and leave room for admin tasks. Traffic routing becomes automated too. A reverse proxy like Traefik or Nginx polls /health/ready actively and removes unready replicas from rotation. Here's the crucial part: idempotency keys must live in shared durable storage, not in-memory state. Client retries'll likely hit a different replica. You'll want wider jitter on reconnect backoff, or use a proxy like ProxySQL. This prevents all replicas from hammering the database at the exact same millisecond when it comes back online. |
|
Keep the process alive and reconnect. Terminating on every database blip is what creates restart loops, and your readiness probe is already doing the right job by flipping to 503 while liveness stays 200. For the reconnect path:
For the ambiguous write — commit may have happened but the acknowledgement was lost — the answer is an idempotency key written into the same transaction as the data. Retry with the same key; the database either returns the original result or rejects the duplicate. Without that, no amount of reconnect logic makes the retry safe. Test with fault injection: stop each container mid-request, restore it, and assert (a) no restart loop, (b) readiness recovers, (c) no duplicate rows after retries, and (d) SIGTERM drains in-flight work. Tools like Toxiproxy or a Compose network cut work well on a single host. With multiple API instances, add a shared idempotency store and expect readiness to be per-instance. |
|
Good setup already — the fact that readiness recovered to 200 without a restart tells you the reconnect path works, so I would keep the process alive rather than terminating on a mid-run outage. Terminating only helps when the process itself is corrupted; for a database blip it just creates the restart loop you want to avoid. A few things that complement the answers above:
|
Uh oh!
There was an error while loading. Please reload this page.
🏷️ Discussion Type
Question
Body
We are building a shared Node.js/Express backend using Docker Compose with MySQL, MongoDB, and Redis.
Our current setup:
/health/livechecks whether the HTTP application responds./health/readychecks database availability and returns 503 when a dependency is unavailable.restart: unless-stoppedand handles SIGTERM for graceful shutdown.We tested stopping MySQL: readiness returned 503. After restoring MySQL, readiness returned 200 without manually restarting the API.
We would like advice on designing the next level of failure recovery:
When a database becomes unavailable after startup, should the API remain alive and reconnect, or terminate so Docker restarts it? What criteria should determine that choice?
In particular:
We are asking about a single-host Docker Compose deployment first. We would appreciate explanations of the trade-offs, especially where the approach should change when moving to multiple API instances.
Guidelines
All reactions