Sub topic 13
Why Applications Should Still Retry Connections
This chapter assumes you can read a compose.yaml, know the depends_on long syntax, and have written a basic healthcheck. It explains why condition: service_healthy reduces startup failures but does not remove the need for retry logic inside your application.
What Compose Guarantees
Compose controls order at startup only. With condition: service_healthy, it starts web after db reports healthy. It does not check the database again after that. It also does not restart web when db becomes unavailable later.
Compose gives you a good starting point. The application still has to handle the situations below.
Situations Compose Does Not Cover
- Dependency restarts. If
dbcrashes and restarts,webkeeps running with connections that are now broken. - Network blips. A dropped packet or a brief DNS failure can break a connection on a healthy system.
- Different deployments. In Kubernetes, ECS, or a managed database,
depends_ondoes not exist. The same image must work there. - Check mismatch. A healthcheck may test less than your app needs.
pg_isreadyconfirms the server accepts connections. It does not confirm that your database, user, or schema exists. - Manual starts. Someone runs
docker compose up webordocker compose restart db, and the ordering you planned is bypassed or interrupted.
A Retry Pattern
A sound retry loop has three parts: a limit on attempts, a delay that grows between attempts, and a clear error when it gives up. The example below uses only the Python standard library and a generic connection function.
import time
def connect_with_retry(connect, attempts=8, base_delay=0.5, max_delay=10.0):
"""Call connect() until it succeeds or attempts run out."""
delay = base_delay
for attempt in range(1, attempts + 1):
try:
return connect()
except OSError as error:
if attempt == attempts:
raise RuntimeError(
f"gave up after {attempts} attempts: {error}"
) from error
print(f"attempt {attempt} failed ({error}); retrying in {delay:.1f}s")
time.sleep(delay)
delay = min(delay * 2, max_delay)
if __name__ == "__main__":
import socket
def connect():
return socket.create_connection(("db", 5432), timeout=2)
connection = connect_with_retry(connect)
print("connected")
connection.close()Replace OSError with the exception your database driver raises for connection failures. Do not retry on errors that retrying cannot fix, such as a wrong password.
Combine Both Layers
Use the layers together. depends_on with service_healthy avoids a noisy startup where the app fails several times before the database is ready. Retries keep the app alive afterward.
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: example
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
web:
image: myapp:latest
restart: unless-stopped
depends_on:
db:
condition: service_healthyThe restart: unless-stopped policy is a last resort. If the retry loop gives up and the process exits, Docker starts the container again. This turns a permanent failure into repeated attempts, so check the logs if web restarts often.
Common Errors
- Retrying forever with no delay. This floods logs and the dependency. Use a delay and a cap.
- Retrying only at startup. Wrap the code that runs queries, or use a connection pool that validates connections, so failures after startup are handled too.
- Retrying non-transient errors. An authentication failure will fail every time. Fail fast and show the message.
- Replacing the healthcheck with retries. Without a healthcheck,
docker compose pscannot tell you whether the dependency is ready.
Exercise
A team uses depends_on with condition: service_healthy for web and db. After a database restart at midnight, web returns errors until someone restarts it by hand. What is missing, and why did the Compose configuration not prevent this?
Show answer
The application lacks connection retry logic, or a pool that discards broken connections. service_healthy is evaluated only when Compose starts web. Compose does not restart web or re-check db afterward, so the existing connections stay broken. Adding a retry with a growing delay lets web reconnect once db is ready again.