ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 6 · Databases, APIs & Integration
  4. Volume I
  5. Database Architecture
Book 6 · Volume I — Database Fundamentals & Relational Data Modeling · Topic 1.3

Database Architecture

Client/server, database process, connection, query processing and storage

9 min readStage 3 · Systems8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — One Request End to End
  5. 4A. Deep Dive — Connection Architecture at Scale
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 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.

Client/server: from Java code to the database
Figure 1 — Client/server: from Java code to the database
ElementRole
ClientApplication (via driver) or tool sending SQL
ConnectionAuthenticated session over TCP/TLS or Unix socket
Server processesHandle sessions and background work
Shared memoryBuffer pool, WAL buffers, locks
Query processorParser, rewriter, planner/optimizer, executor
StorageData files (pages), indexes, WAL, temp files
Table 1 — Architectural elements

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

AspectDetail
ProtocolPostgreSQL frontend/backend protocol; MySQL protocol; TDS (SQL Server)
TransportTCP (TLS recommended), Unix domain sockets locally
AuthenticationPassword (SCRAM-SHA-256), certificates, IAM tokens (cloud)
DriverJDBC driver translates Java calls into protocol messages
Round tripsEach statement (or batch) is one or more network round trips
Table 2 — Client/server interaction

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

PostgreSQL process architecture
Figure 2 — PostgreSQL process architecture
ModelDBMSImplication
Process per connectionPostgreSQLEach connection costs memory (~several MB); hundreds OK, thousands need pooling
Thread per connectionMySQL, SQL ServerLighter than processes; still limits
Shared-nothing distributedCitus, CockroachDB, YugabyteQueries fan out across nodes
Table 3 — Process models
PostgreSQL background processJob
CheckpointerPeriodically writes dirty pages; limits recovery time
Background writerTrickles dirty pages to disk
WAL writerFlushes WAL buffers
AutovacuumRemoves dead row versions, updates statistics
WAL sender/receiverStreaming replication
Table 4 — Background processes

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.

YAML
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 thumbExplanation
Total connections = instances × pool size10 pods × 20 = 200 server connections
Keep below server max_connections with headroomAdmin, replication, migrations need connections
Pool size ≈ cores × 2 (+ disk factor) per DB nodeMore connections ≠ more throughput; contention rises
Use PgBouncer (transaction pooling) for many instancesMultiplex many client connections onto few server ones
Hold connections brieflyNo remote calls inside transactions
Table 5 — Connection sizing

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

Query processing pipeline
Figure 3 — Query processing pipeline
StageWhat happens
ParseSQL text → parse tree; syntax errors reported
Analyse / rewriteResolve names and types; expand views; apply rules
Plan (optimize)Enumerate access paths and join orders; estimate costs from statistics; choose cheapest
ExecuteRun plan nodes (scans, joins, sorts, aggregates) pulling tuples
ReturnStream rows to client
Table 6 — Query processing stages
SQL
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;
TEXT
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 ms

Prepared statements (JDBC PreparedStatement) avoid re-parsing and enable plan caching; always use bind parameters — also for SQL-injection safety.

3.5 Storage

Storage: pages, buffers and files
Figure 4 — Storage: pages, buffers and files
StructurePostgreSQL detail
Page8 KB unit of I/O; header, item pointers, tuples
Heap fileTable data as a set of pages (one file per 1 GB segment)
Index filesB-tree (default), GIN, GiST, BRIN, hash
TOASTOut-of-line storage for large values (> ~2 KB)
Shared buffersPage cache in shared memory (plus OS page cache)
WALSequential log in 16 MB segments
Visibility map / free space mapHelp vacuum and index-only scans
Table 7 — Storage structures

4How It Works Internally — One Request End to End

StepComponentCost driver
1 orderRepository.findByCustomer(id)Spring Data → Hibernate → JDBCObject mapping
2 Borrow connectionHikariCPPool wait if exhausted
3 Send prepared statementDriver → networkRound-trip latency
4 Parse/plan (or reuse plan)Backend processPlanning time
5 Execute index scanExecutor → buffer managerPages read (hit vs disk)
6 Return rowsNetworkRow count × width
7 Map to entities, return connectionHibernate, poolHydration cost
Table 8 — Request anatomy

4ADeep Dive — Connection Architecture at Scale

SituationProblemArchitecture
50 app pods × 20 connections1,000 backends → memory, context switchingPgBouncer in transaction mode; smaller pools
Serverless functionsConnection storms on cold startRDS Proxy / PgBouncer; HTTP data APIs
Read-heavy trafficPrimary saturated by readsRead replicas + routing (@Transactional(readOnly=true) → replica datasource)
Long transactionsHold connections and locks; block vacuumShort transactions; no external calls inside
Idle-in-transaction sessionsBloat, locksidle_in_transaction_session_timeout
Table 9 — Connection scaling patterns
JAVA
// 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 connecting

Caveat: replicas lag; route only reads that tolerate staleness (lists, reports) — not "read-your-own-write" flows immediately after an update.

5APIs / Features / Syntax

Tool / APIUse
pg_stat_activityCurrent sessions, states, waits
pg_stat_statementsAggregated query statistics
EXPLAIN (ANALYZE, BUFFERS)Actual plan and I/O
SHOW max_connections, shared_buffersCapacity settings
HikariCP metrics (Micrometer)Pool usage, wait time, timeouts
JDBC PreparedStatement, batch APIsEfficient statements
Hibernate hibernate.jdbc.batch_size, order_insertsBatched writes
Table 10 — Observability and APIs
SQL
-- 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

InputValue
DB server16 vCPU, NVMe storage
Target DB concurrency~40 active queries (≈ 2–3 × cores)
App instances8 (autoscale to 16)
Admin/replication reserve20
Table 11 — Sizing inputs
DecisionValue
Pool per instance5 (16 × 5 = 80 max)
PgBouncerTransaction mode, 60 server connections
max_connections150
connection-timeout500 ms (fail fast; alert on waits)
Table 12 — Resulting configuration

6.4 Worked example — reading a slow plan

TEXT
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
ClueMeaningFix
Seq Scan with huge "Rows Removed"No usable index on customer_idCREATE INDEX CONCURRENTLY ix_order_customer ON purchase_order (customer_id);
read=60311Many pages from diskIndex reduces to a few pages
After fixIndex Scan … Execution Time: 0.2 ms4000× faster
Table 13 — Diagnosing with EXPLAIN

6.5 Worked example — reducing round trips

PatternRound trips for 100 orders with lines
N+1 (lazy loading lines per order)101
JOIN FETCH / entity graph1
Batch fetching (@BatchSize(50))3
DTO projection query1
Table 14 — Round-trip reduction
JAVA
@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

MetricWhy
Pool active/idle/pending (Hikari)Detect saturation
DB CPU, IOPS, buffer hit ratioServer capacity
Top queries by total time (pg_stat_statements)Where to optimise
Long-running / idle-in-transaction sessionsLocks, bloat
Replication lagReplica freshness
Table 15 — Key metrics

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_statements dashboards).
  • Scale reads with replicas and caches consciously; scale writes by design (partitioning, fewer hot rows).

10Interview Questions & Answers

Q1L1 · BasicConcept

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.

Q2L1 · BasicConcept

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.

Q3L2 · IntermediateInternals

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.

Q4L2 · IntermediateInternals

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.

Q5L3 · Senior EngineerInternals

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.

Q6L3 · Senior EngineerDesign

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.

Q7L4 · Technical ArchitectTrade-off

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.

Q8L5 · Solution ArchitectDesign

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.