- Chapter
- Chapter 1 — Database Fundamentals
- Prerequisites
- Topics 1.1–1.2
- You will be able to
- Explain the client/server architecture of an RDBMS, describe PostgreSQL's process and memory model, size and manage connections and pools from Java, follow a query through parsing, planning and execution, and understand how pages, buffers, WAL and data files work together
- Covers
- Client/server; Database process; Connection; Query processing; Storage
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — One Request End to End
- 4A. Deep Dive — Connection Architecture at Scale
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
Database architecture describes how a database system is organised at runtime: how clients connect, which processes and memory structures serve them, how SQL is processed, and how data is stored on disk.

| Element | Role |
|---|---|
| Client | Application (via driver) or tool sending SQL |
| Connection | Authenticated session over TCP/TLS or Unix socket |
| Server processes | Handle sessions and background work |
| Shared memory | Buffer pool, WAL buffers, locks |
| Query processor | Parser, rewriter, planner/optimizer, executor |
| Storage | Data files (pages), indexes, WAL, temp files |
2Why It Exists
Centralising data in a server lets many clients share it safely, lets the DBMS cache hot data in memory for everyone, and lets expensive capabilities (planning, locking, logging) be implemented once. The client/server split also allows independent scaling: many application instances, one (or a few) database servers with replicas.
3Core Concepts
3.1 Client/server
| Aspect | Detail |
|---|---|
| Protocol | PostgreSQL frontend/backend protocol; MySQL protocol; TDS (SQL Server) |
| Transport | TCP (TLS recommended), Unix domain sockets locally |
| Authentication | Password (SCRAM-SHA-256), certificates, IAM tokens (cloud) |
| Driver | JDBC driver translates Java calls into protocol messages |
| Round trips | Each statement (or batch) is one or more network round trips |
Round trips matter: N+1 query patterns multiply round trips; batching (addBatch/executeBatch, JdbcClient with batch updates, Hibernate jdbc.batch_size) reduces them.
3.2 Database process

| Model | DBMS | Implication |
|---|---|---|
| Process per connection | PostgreSQL | Each connection costs memory (~several MB); hundreds OK, thousands need pooling |
| Thread per connection | MySQL, SQL Server | Lighter than processes; still limits |
| Shared-nothing distributed | Citus, CockroachDB, Yugabyte | Queries fan out across nodes |
| PostgreSQL background process | Job |
|---|---|
| Checkpointer | Periodically writes dirty pages; limits recovery time |
| Background writer | Trickles dirty pages to disk |
| WAL writer | Flushes WAL buffers |
| Autovacuum | Removes dead row versions, updates statistics |
| WAL sender/receiver | Streaming replication |
3.3 Connection
A connection is an authenticated session with its own state (transaction, settings, prepared statements, temp tables). Opening one is expensive (TCP + TLS + auth + backend process), so applications use connection pools.
spring:
datasource:
hikari:
maximum-pool-size: 20 # per application instance
minimum-idle: 5
connection-timeout: 500 # ms to wait for a free connection
max-lifetime: 1800000 # recycle before server/proxy timeouts
leak-detection-threshold: 20000| Sizing rule of thumb | Explanation |
|---|---|
| Total connections = instances × pool size | 10 pods × 20 = 200 server connections |
Keep below server max_connections with headroom | Admin, replication, migrations need connections |
| Pool size ≈ cores × 2 (+ disk factor) per DB node | More connections ≠ more throughput; contention rises |
| Use PgBouncer (transaction pooling) for many instances | Multiplex many client connections onto few server ones |
| Hold connections briefly | No remote calls inside transactions |
Virtual threads note: with thousands of virtual threads, the pool (not threads) limits DB concurrency — which is desirable; size the pool for the database, not for the thread count.
3.4 Query processing

| Stage | What happens |
|---|---|
| Parse | SQL text → parse tree; syntax errors reported |
| Analyse / rewrite | Resolve names and types; expand views; apply rules |
| Plan (optimize) | Enumerate access paths and join orders; estimate costs from statistics; choose cheapest |
| Execute | Run plan nodes (scans, joins, sorts, aggregates) pulling tuples |
| Return | Stream rows to client |
EXPLAIN (ANALYZE, BUFFERS)
SELECT c.full_name, count(*) AS orders
FROM customer c JOIN purchase_order o ON o.customer_id = c.customer_id
WHERE c.city = 'Pune' AND o.placed_at >= now() - interval '30 days'
GROUP BY c.full_name;HashAggregate (actual time=4.1..4.3 rows=212)
-> Hash Join (actual time=0.9..3.7 rows=1840)
Hash Cond: (o.customer_id = c.customer_id)
-> Index Scan using ix_order_placed_at on purchase_order o (rows=9120)
-> Hash -> Index Scan using ix_customer_city on customer c (rows=640)
Buffers: shared hit=412 read=3
Planning Time: 0.3 ms Execution Time: 4.5 msPrepared statements (JDBC PreparedStatement) avoid re-parsing and enable plan caching; always use bind parameters — also for SQL-injection safety.
3.5 Storage

| Structure | PostgreSQL detail |
|---|---|
| Page | 8 KB unit of I/O; header, item pointers, tuples |
| Heap file | Table data as a set of pages (one file per 1 GB segment) |
| Index files | B-tree (default), GIN, GiST, BRIN, hash |
| TOAST | Out-of-line storage for large values (> ~2 KB) |
| Shared buffers | Page cache in shared memory (plus OS page cache) |
| WAL | Sequential log in 16 MB segments |
| Visibility map / free space map | Help vacuum and index-only scans |
4How It Works Internally — One Request End to End
| Step | Component | Cost driver |
|---|---|---|
1 orderRepository.findByCustomer(id) | Spring Data → Hibernate → JDBC | Object mapping |
| 2 Borrow connection | HikariCP | Pool wait if exhausted |
| 3 Send prepared statement | Driver → network | Round-trip latency |
| 4 Parse/plan (or reuse plan) | Backend process | Planning time |
| 5 Execute index scan | Executor → buffer manager | Pages read (hit vs disk) |
| 6 Return rows | Network | Row count × width |
| 7 Map to entities, return connection | Hibernate, pool | Hydration cost |
4ADeep Dive — Connection Architecture at Scale
| Situation | Problem | Architecture |
|---|---|---|
| 50 app pods × 20 connections | 1,000 backends → memory, context switching | PgBouncer in transaction mode; smaller pools |
| Serverless functions | Connection storms on cold start | RDS Proxy / PgBouncer; HTTP data APIs |
| Read-heavy traffic | Primary saturated by reads | Read replicas + routing (@Transactional(readOnly=true) → replica datasource) |
| Long transactions | Hold connections and locks; block vacuum | Short transactions; no external calls inside |
| Idle-in-transaction sessions | Bloat, locks | idle_in_transaction_session_timeout |
// Routing reads to a replica with Spring's AbstractRoutingDataSource
public class ReadWriteRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? "replica" : "primary";
}
}
// wrap in LazyConnectionDataSourceProxy so the read-only flag is known before connectingCaveat: replicas lag; route only reads that tolerate staleness (lists, reports) — not "read-your-own-write" flows immediately after an update.
5APIs / Features / Syntax
| Tool / API | Use |
|---|---|
pg_stat_activity | Current sessions, states, waits |
pg_stat_statements | Aggregated query statistics |
EXPLAIN (ANALYZE, BUFFERS) | Actual plan and I/O |
SHOW max_connections, shared_buffers | Capacity settings |
| HikariCP metrics (Micrometer) | Pool usage, wait time, timeouts |
JDBC PreparedStatement, batch APIs | Efficient statements |
Hibernate hibernate.jdbc.batch_size, order_inserts | Batched writes |
-- Who is connected and what are they waiting on?
SELECT pid, usename, application_name, state, wait_event_type, wait_event,
now() - xact_start AS xact_age, left(query, 60) AS query
FROM pg_stat_activity
WHERE datname = 'shop' ORDER BY xact_age DESC NULLS LAST;6Practical Examples
6.1 Pool exhaustion
A checkout service called a payment API inside @Transactional; under load all 20 connections were held for seconds and requests timed out waiting for the pool. Moving the remote call outside the transaction reduced connection hold time from ~1.2 s to ~15 ms.
6.2 Too many connections
Autoscaling to 60 pods × pool 30 exceeded max_connections=500; new pods failed to start. PgBouncer in transaction mode plus pool size 10 per pod stabilised the system.
6.3 Worked example — sizing connections for a service
| Input | Value |
|---|---|
| DB server | 16 vCPU, NVMe storage |
| Target DB concurrency | ~40 active queries (≈ 2–3 × cores) |
| App instances | 8 (autoscale to 16) |
| Admin/replication reserve | 20 |
| Decision | Value |
|---|---|
| Pool per instance | 5 (16 × 5 = 80 max) |
| PgBouncer | Transaction mode, 60 server connections |
max_connections | 150 |
connection-timeout | 500 ms (fail fast; alert on waits) |
6.4 Worked example — reading a slow plan
Seq Scan on purchase_order (actual time=0.02..812.4 rows=37 loops=1)
Filter: (customer_id = 101)
Rows Removed by Filter: 4,812,113
Buffers: shared hit=1204 read=60311
Execution Time: 813.1 ms| Clue | Meaning | Fix |
|---|---|---|
Seq Scan with huge "Rows Removed" | No usable index on customer_id | CREATE INDEX CONCURRENTLY ix_order_customer ON purchase_order (customer_id); |
read=60311 | Many pages from disk | Index reduces to a few pages |
| After fix | Index Scan … Execution Time: 0.2 ms | 4000× faster |
6.5 Worked example — reducing round trips
| Pattern | Round trips for 100 orders with lines |
|---|---|
| N+1 (lazy loading lines per order) | 101 |
JOIN FETCH / entity graph | 1 |
Batch fetching (@BatchSize(50)) | 3 |
| DTO projection query | 1 |
@Query("select o from Order o join fetch o.lines where o.customer.id = :customerId")
List<Order> findWithLines(@Param("customerId") long customerId);7Common Problems & Mistakes
- Remote calls inside transactions holding connections.
- Oversized pools that overload the database.
- N+1 queries multiplying round trips.
- String-concatenated SQL — no plan reuse, injection risk.
- Ignoring EXPLAIN when queries slow down.
- Routing read-after-write to replicas.
8Performance & Production Considerations
| Metric | Why |
|---|---|
| Pool active/idle/pending (Hikari) | Detect saturation |
| DB CPU, IOPS, buffer hit ratio | Server capacity |
Top queries by total time (pg_stat_statements) | Where to optimise |
| Long-running / idle-in-transaction sessions | Locks, bloat |
| Replication lag | Replica freshness |
9Architecture & Design Considerations
- Treat connections as a scarce shared resource; size pools from the database outward.
- Keep transactions short; never do I/O to other systems inside them.
- Make query plans visible (EXPLAIN in reviews,
pg_stat_statementsdashboards). - Scale reads with replicas and caches consciously; scale writes by design (partitioning, fewer hot rows).
10Interview Questions & Answers
What is a database connection?
A database connection is an authenticated session between one client and the database server, usually over TCP with TLS or a local Unix socket. In PostgreSQL each connection gets its own backend process. The session carries state: the current transaction, its isolation level, session settings such as search_path and time zone, prepared statements, temporary tables and any advisory locks. Everything a JDBC Connection does runs inside that one session, which is why a transaction can never span two connections. Opening one is expensive, because it needs a TCP and TLS handshake, authentication and a new backend, so Java applications borrow connections from a pool instead.
Why use a connection pool?
Opening a connection costs several round trips for TCP, TLS and SCRAM authentication, plus forking a backend process in PostgreSQL, which can add tens of milliseconds to every request. A pool such as HikariCP keeps a bounded set of open connections and lends them out for the length of a unit of work, so the cost is paid once. The bound matters as much as the reuse: it caps how many queries one instance can push at the database, so a traffic spike queues briefly in the application instead of overloading the server. Pools also validate, recycle and reset connections and expose wait-time metrics for alerting.
What are the stages of query processing?
PostgreSQL processes a statement in five stages. The parser checks syntax and builds a parse tree. Analysis resolves table and column names and types against the catalogue, and the rewriter expands views and applies rules. The planner then enumerates access paths such as sequential scan, index scan or bitmap scan, join orders and join methods, estimates their cost from table statistics and picks the cheapest plan. The executor runs that plan as a tree of nodes that pull rows from each other, and results are streamed back to the client. With prepared statements the parse and plan work can be reused, so only execution is repeated.
What does EXPLAIN ANALYZE show?
Plain EXPLAIN shows only the planner's chosen plan with estimated costs and row counts. EXPLAIN ANALYZE actually executes the statement and adds, for every plan node, the real start-up and total time, the actual rows produced and how many loops ran. Comparing estimated with actual rows is the key diagnostic: a large mismatch means stale statistics or a misleading predicate, and that leads to bad join orders. Adding BUFFERS shows shared hit pages served from cache versus read pages fetched from disk, which explains whether a query is slow because of I/O. Because it really runs the query, wrap DML in a transaction and roll back.
Why is PostgreSQL's process-per-connection model relevant to Java apps?
PostgreSQL forks a separate backend process for every connection, and each one costs memory for its stack, catalogue caches and work_mem allocations, often several megabytes even when idle. Hundreds of connections are fine; thousands cause memory pressure, context switching and slower snapshot work. Java estates hit that limit easily, because every pod has its own HikariCP pool and autoscaling multiplies them: 60 pods with 20 connections each is 1,200 backends. The answer is small pools per instance and, at scale, PgBouncer in transaction mode or RDS Proxy to multiplex many client connections onto a few dozen server connections. Virtual threads do not change this; the pool remains the limit.
How do you size a HikariCP pool?
Size the pool from what the database can actually execute, not from the number of request threads. A database node runs efficiently with only a few active queries per CPU core, so a 16-core server might be saturated at around 40 concurrent queries. Divide that budget across the maximum number of application instances after autoscaling, keep the total well below max_connections with headroom for admin, replication and migrations, and you typically end with 5 to 10 connections per pod. Set a short connection-timeout so waits fail fast, and watch Hikari's pending and wait-time metrics. Above the database's sweet spot, more connections increase contention and reduce throughput.
How do you scale read traffic?
First remove reads that do not need to happen: fix N+1 patterns, add the right indexes and use DTO projections, because a cheaper query scales better than more hardware. Then cache hot, rarely changing data in the application or Redis with a clear invalidation or TTL policy. For the remaining load, add read replicas and route staleness-tolerant queries such as lists, search pages and reports to them, for example through an AbstractRoutingDataSource keyed on @Transactional(readOnly = true) and wrapped in LazyConnectionDataSourceProxy. Keep read-your-own-write flows on the primary because replicas lag. Heavy analytics belong in a separate reporting store, not on OLTP replicas.
What architectural rules prevent common database incidents?
Most database incidents in Java systems are connection, plan or I/O problems, so I set rules for each. Transactions stay short, and no remote HTTP or messaging calls happen inside them, because that is how pools get exhausted. Pools are bounded and sized from the database outward, with PgBouncer or RDS Proxy once instance counts grow. Queries are reviewed with EXPLAIN (ANALYZE, BUFFERS) for key paths, N+1 is caught by tests or Hibernate statistics, and indexes ship through Flyway migrations created concurrently. Finally, dashboards and alerts cover pool wait time, pg_stat_statements top queries, idle-in-transaction sessions and replication lag, with timeouts like idle_in_transaction_session_timeout as a safety net.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.