Database connection and recovery
Connect applications without overwhelming the database
A connection pool keeps a bounded set of database sessions available for reuse. Opening a new session for every request adds authentication and connection setup overhead; leaving too many open uses memory and other server resources. A pool is not a query cache and cannot make slow queries faster by itself. Each application process may own a separate pool, so count processes, not merely virtual machines.
Imagine six application processes with a pool maximum of 20 connections each. The database permits 150 connections and 30 are reserved for maintenance and other workloads. Application budget = 150 - 30 = 120. Six pools can consume 120, leaving no slack within that budget. If autoscaling adds two processes, eight pools can demand 160, exceeding the budget by 40. With eight processes, a maximum of 15 per pool fits the 120 allocation; choose a lower cap if additional headroom is required. This is a maximum-capacity model, not a measurement of active sessions. Some engines reserve connections differently.
Diagnose pool exhaustion and failed connections
Monitor pool wait time, active and idle sessions, connection errors, transaction duration, CPU, locks and query latency. If all connections are occupied by slow queries, increasing the pool may make contention worse. Keep transactions short, index useful access paths, measure and tune queries, release sessions in all code paths, and use bounded acquisition timeouts. Avoid unbounded queues and retries. An external pooler can reduce backend sessions but some pooling modes change session-state semantics; verify prepared statements, temporary tables and driver compatibility.
Follow a private connection from the application through DNS, network routes, firewall policy, TLS certificate validation, authentication and database authorization. If DNS fails, inspect the private DNS zone; if TCP times out, check reachability and policy; if TLS rejects the peer, fix the trust configuration or hostname; if login succeeds but a query is denied, review database grants. Keep the port private and use least privilege, rotated secrets or supported short-lived identity. Never print real connection strings, disable certificate verification or open public access as a troubleshooting shortcut.
Plan for failover and ambiguous writes
During failover existing sessions may break even if the service keeps the same logical endpoint. Applications must discard broken pooled sessions, reconnect using the supported endpoint and tolerate temporary errors. Use bounded retry with backoff and jitter; observe the total request deadline. A lost response after COMMIT is ambiguous: the write may already have succeeded. Retrying an order insert blindly can create duplicate business actions. Use a stable request identifier with a uniqueness constraint, verify the existing outcome, and retry only according to a reviewed transaction policy.
Keep database engine upgrades separate from application deploys where practical. Review support dates, extension compatibility, maintenance windows and rollback or restore options. Rehearse major upgrades against a restored copy and run migration and application tests; an automated backup does not prove a downgrade is supported.
Turn recovery targets into a restore drill
Recovery point objective (RPO) is the tolerable amount of lost work expressed as time; recovery time objective (RTO) is the target time to restore service. Suppose an accidental deletion occurs at 10:20, the selected safe point is 10:18, and the business allows 5 minutes of loss and 30 minutes of recovery. The time gap is 2 minutes. If provisioning takes 12 minutes, verification takes 8 and application cutover takes 7, modeled recovery takes 27 minutes. Both targets are met in this example. This does not imply only two minutes of records are affected or a provider guarantees these times. Valid writes after the selected point require reconciliation.
Restore into an isolated destination, check encryption, access rules, engine compatibility and schema, compare expected records and totals, test representative application queries, then plan a controlled cutover. Keep the original until data reconciliation, rollback and retention requirements are satisfied. Azure SQL Database PITR creates a new database; RDS and Cloud SQL have their own restore workflows. Verify destination configuration separately; never assume a restore inherits every operational setting.
Run a local backup and restore experiment
The authoring fixture uses Python 3.13.5 and SQLite 3.46.1, in memory only. It is an independent local exercise, not a ByteMind runner example or a test of provider PITR. Follow the previous lesson's setup, commit the first purchase (stock 2, order 101), and copy the committed database into a second SQLite connection using Connection.backup. Next commit a deliberate deletion of order 101 in the original database. The live order count is now 0. Restore by copying the backup into a third connection; re-enable foreign-key enforcement and query the restored data. Stock is 2 and order 101 exists. The original remains unchanged by the restore.
This simple backup copies one saved state; it does not simulate transaction-log replay, concurrent production writes, cloud encryption, network failover or measured RTO. Check row values and referential integrity, not just whether the restore command succeeds. To run the included fixture locally, execute python validate-package.py in the extracted package; no credentials, network or disk database are required. The fixture and expected results are in lab-fixtures/offline/chapter-20-relational-databases.json.
Practice and recap
Calculate a pool budget for a new replica count; choose the safe recovery point and compare the modeled recovery time with business targets. Explain why a successful database connection does not prove the application is authorized, and why replaying an ambiguous checkout can be unsafe. Next: NoSQL, distributed data and caching.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database connection and recovery — knowledge check
Choose the best answer for each offline scenario.
A server permits 150 connections, 30 reserved. Eight processes need equal pools. What is the maximum per process with no extra headroom?
A private database hostname cannot resolve. What should you inspect first?
A checkout loses its response just after a possible COMMIT. What is safest?
A deletion occurs at 10:20 and the chosen safe point is 10:18. What is the recovery-point gap?
Which is evidence of a useful restore test?