4 Databases durable jobs and reliable automation
A relational database stores structured data and enforces constraints. PostgreSQL is appropriate when you need multiple clients, transactional updates, indexes, and mature operations.
Outcome: reason about persistence, duplicate delivery, retries, and recovery. Prerequisites: the local project. Environment: SQLite for introductory work and the PostgreSQL Compose deployment for operational exercises.
Choose storage by the contract
A relational database stores structured data and enforces constraints. PostgreSQL is appropriate when you need multiple clients, transactional updates, indexes, and mature operations. SQLite is useful for local and embedded workloads with a different concurrency and deployment model. A cache speeds reads but should not silently become the only copy of important data. Object storage holds blobs such as reports or uploaded files; store their metadata and access policy separately.
Define what must remain true before choosing a product. For this service: one logical submission has one durable job, one tenant cannot read another's data, and an interrupted worker cannot silently lose accepted work. These requirements lead to a unique constraint, tenant-scoped queries, committed storage before acknowledgment, and expiring claims.
SQL concepts
A table contains rows with named columns. A primary key uniquely identifies a row. A unique constraint prevents duplicate values or combinations. An index helps selected reads but adds write/storage cost. A transaction groups operations that should commit together or roll back together. Isolation governs what concurrent transactions observe; it is not a substitute for designing races deliberately.
Use parameterized SQL or an ORM that binds parameters. Never assemble a query by inserting user text into SQL. The example's SQLAlchemy expressions bind values. Dynamic sort fields or table names also need allowlists because not every SQL element can be parameterized as a value.
Examine a query plan on representative data before adding indexes. An index on every column is rarely the answer. For the job queue, measure how many rows the claim query scans, how long transactions hold locks, and whether completed-job retention prevents the active table from growing indefinitely.
Schema changes without breaking a release
The reference uses Alembic revisions for initialization and upgrade; create_all is used only by isolated test fixtures. Chapter 15 explains migration ownership, existing-v2 baseline adoption and the backfill. Use a separate migration identity and a runtime identity with only the operations it needs. Back up and rehearse on representative data before a change that rewrites or drops important data.
A safe pattern is expand, migrate, contract. Add a nullable replacement column first. Deploy code that handles old and new rows. Backfill in bounded batches with progress tracking. Verify counts and constraints. Switch reads. Remove the old column only after the rollback window closes. Rolling application code backward cannot restore a dropped column's lost contents.
Exercise: add an optional job label through a migration, test the old API against the expanded schema, and rehearse the backfill twice. The second run should be safe. Record what happens if it stops halfway through.
Connections and transactions
A connection pool reuses database connections. Its size is not free capacity: total connections across API replicas, workers, migrations, and administration must fit the database's limit. Set timeouts so a dependency problem does not hold every request indefinitely. Roll back failed transactions before reuse.
Keep network calls outside a database transaction where possible. A slow model provider should not hold row locks while generating text. Record work intent, commit, perform the external operation, and reconcile its result using a durable identifier. Design for a crash between each step.
The job state machine
A worker atomically changes an eligible row to running, increments its attempt count, and writes a new claim token and lease expiration. It performs the small computation outside the transaction. Completion updates the row only if that claim still owns it. This prevents an old worker from overwriting a newer claim's result.
The lease is a promise about how long a worker owns the job, not proof that the worker has stopped. If work can outlive the lease, add bounded execution and lease renewal with ownership checks. Fencing the database update cannot prevent a timed-out worker from sending an external email or payment. Downstream operations need their own idempotency contract.
The sample handler is pure and finishes quickly. It has three attempts, a short retry delay, and a 30-second claim lease. A crashed final attempt becomes terminal after expiry. Failed jobs remain visible; an operator should investigate before scheduling an intentional new request. Do not automatically replay permanent validation or authorization errors.
Delivery semantics
“At least once” means work may be delivered again. “At most once” may lose work when acknowledgment and execution race. Exactly-once business effects require careful transactional boundaries or a downstream idempotency mechanism; putting a queue in front of an API does not magically provide them.
An inbox records received event IDs under a unique constraint before processing. An outbox records outgoing event intent in the same transaction as the business update, then publishes asynchronously. Both patterns reduce the gap between “we stored the data” and “we sent the event.” Consumers still need duplicate handling.
Use exponential backoff with jitter for transient upstream failure, bound the number and total duration of retries, and respect retry guidance. Retry storms can turn a partial outage into a complete one. A dead-letter queue is a place to inspect exhausted work, not a wastebasket nobody monitors.
Webhook receiver design
A webhook is an HTTP notification from another service. Its delivery may be duplicated, delayed, or out of order. Validate the provider's signature over the exact raw bytes, reject an unacceptable timestamp, compare signatures safely, and record the provider's event ID transactionally. A signature proves origin/integrity under a shared secret; it does not make the event's business action automatically authorized.
Respond successfully after durable receipt, then process asynchronously. If you acknowledge before committing and crash, the provider may stop retrying an event you lost. If the same event arrives twice, return the existing receipt without duplicating the action. When event order matters, compare resource versions or fetch authoritative state instead of trusting arrival order.
Worked implementation: /webhooks/demo now verifies HMAC over raw bytes and timestamp, enforces a five-minute window and persists an event-keyed job as its durable inbox. Chapter 15 and tests/test_v3.py cover the signed protocol, stale timestamps, modified bodies and duplicate delivery. Adapt the signature algorithm to the actual provider contract before integration.
Schedules and time
Store event instants with an explicit time convention, normally UTC. Keep the user's business timezone separately for schedules. Daylight-saving transitions can skip or repeat local times. Define missed-run policy: skip, catch up once, or replay every missed period. Give each scheduled run a deterministic identity so two scheduler instances cannot create duplicate effects.
A cron trigger should enqueue work and exit. Long-running work belongs in the worker. Prevent overlapping runs where the business contract requires serialization. Measure schedule delay and completion separately.
Backup and restore
A backup is useful only if you can restore it. Define the recovery point objective, the maximum acceptable data loss, and the recovery time objective, the maximum acceptable interruption. A daily dump cannot satisfy a five-minute loss target. Replication improves availability but may replicate an accidental deletion; it is not a substitute for independent backups.
Use a consistent database-native backup method. For PostgreSQL, a custom-format dump can be restored into a separate database. Protect backups as sensitive data, encrypt copies, restrict access, retain versions, and test restoration. The PostgreSQL manual explains dump and restore behavior: [SQL dump](https://www.postgresql.org/docs/current/backup-dump.html).
Local Compose lab, after creating test jobs:
Use a fresh restore database name if one already exists; do not drop a database to make an example pass. Compare representative records as well as counts. A complete restore drill also checks roles, schema privileges, application connectivity, blob references, and encrypted-secret availability. This example restores data into a separate database without switching the running application.
Exit exercise
Stop your worker, queue multiple jobs, restart it, and prove all accepted jobs reach a terminal state. Run concurrent duplicate submissions and prove one logical job exists. Restore a backup into a separate database and compare known results. Explain precisely which external side effects would still be unsafe if you replaced the pure analyzer with an email sender.
Lock in what you just learned (3 quick questions)
EXPLAIN ANALYZE shows Seq Scan on orders for WHERE tenant_id = ? ORDER BY created_at DESC, what is the proper fix?