Database

Database Design and Optimization for Web Applications 2025

DLN Web Studio
2024-07-01
11 min read
0 views
database designSQLNoSQLoptimizationindexingscalability
Database Design and Optimization for Web Applications 2025

Most web application performance problems end up at the database. A slow dashboard, a checkout that times out under load, or an API endpoint that gets slower every month usually traces back to a missing index, an inefficient query pattern, or a schema decision made early and never revisited. This guide covers choosing a database, designing a schema, indexing it well, and keeping it fast and safe as your application grows. Examples use PostgreSQL, but most concepts apply to MySQL and other relational databases too.

Choosing a Database: SQL vs NoSQL

Relational databases (PostgreSQL, MySQL)

For most web applications, from SaaS products to online stores, a relational database is the right default. You get:

  • ACID transactions, so related changes succeed or fail together.
  • Constraints that enforce data integrity at the database level.
  • Flexibility where you need it. PostgreSQL's jsonb type lets you store semi-structured data and index it, so you rarely need a separate document store just for flexible attributes.

Both are solid. PostgreSQL has the richer feature set (partial and expression indexes, jsonb, extensions), while MySQL is common on shared and managed hosting.

NoSQL databases

NoSQL is a broad label covering very different tools:

  • Document stores (MongoDB): good when data is naturally document-shaped and read as whole units. You still need to design for your access patterns.
  • Key-value stores (Redis, Valkey): in-memory and very fast. Ideal for caching, sessions, rate limiting, queues, and leaderboards. Usually not your primary system of record.
  • Wide-column stores (Cassandra) and DynamoDB: built for huge write volume and horizontal scale, at the cost of modeling tables around specific queries.

A practical pattern for many applications is PostgreSQL as the source of truth, plus Redis or Valkey for caching and ephemeral data, adding specialized stores only when a real need appears.

Schema Design

Normalize first

Normalization means storing each fact in one place: orders reference a customer by ID instead of copying the customer's email onto every row. This prevents one copy changing while another doesn't. Third normal form is a good starting point.

Denormalize deliberately

Storing derived or duplicated data can speed up reads but creates a consistency burden. Do it for a measured need, with a clear way to keep it in sync:

  • A cached counter (such as comment_count) updated in the same transaction as the insert.
  • A materialized view refreshed on a schedule for reporting.
  • A snapshot that is supposed to be frozen, like the price stored on an order line at purchase time.

Primary keys: bigint vs UUIDv7

The two sensible choices today are:

  • bigint identity columns: compact (8 bytes), fast, and ordered, but guessable and generated only by the database.
  • UUIDs: globally unique and can be generated anywhere, which suits distributed systems and public-facing IDs. Random UUIDv4 values scatter inserts across the index, which hurts write performance and cache efficiency on large tables. UUIDv7, standardized in RFC 9562 (2024), starts with a timestamp, so new values are roughly sequential and index-friendly. PostgreSQL 18 includes a built-in uuidv7() function. On older versions, generate them in the application or with an extension.

Note that UUIDv7 embeds the creation time, so don't use it where revealing that timestamp is a concern.

Use constraints

Constraints are cheap insurance. Application validation can be bypassed by bugs, scripts, and race conditions; the database can't.

CREATE TABLE customers (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email       text NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);

-- Case-insensitive uniqueness on email
CREATE UNIQUE INDEX customers_email_lower_key ON customers (lower(email));

CREATE TABLE orders (
  id           uuid PRIMARY KEY DEFAULT uuidv7(),  -- PostgreSQL 18+
  customer_id  bigint NOT NULL REFERENCES customers (id),
  status       text NOT NULL DEFAULT 'pending'
               CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
  total_cents  integer NOT NULL CHECK (total_cents >= 0),
  created_at   timestamptz NOT NULL DEFAULT now()
);

Store money as integer cents or numeric, never floating point, and use timestamptz for points in time. PostgreSQL doesn't automatically index foreign key columns, so index orders.customer_id if you query by it.

Indexing Strategies

An index lets the database find rows without scanning the whole table. Each one speeds up some reads but slows every write and uses storage, so index for the queries you actually run.

B-tree indexes

The default B-tree handles equality, ranges, and sorting. Other types serve special cases: GIN for jsonb, arrays, and full-text search; GiST for geometric and range data; BRIN for huge, naturally ordered tables like append-only logs.

Composite index column order

For a multi-column index, order matters. The index is sorted by the first column, then the second within it, and so on. A good rule of thumb is equality columns first, then range or sort columns.

-- Query: a customer's recent orders
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

-- Matching index: equality column first, then the sort column
CREATE INDEX orders_customer_created_idx
  ON orders (customer_id, created_at DESC);

It also serves queries on customer_id alone, but not on created_at alone.

Partial indexes

If queries usually target a small subset of rows, index only that subset:

CREATE INDEX orders_pending_created_idx
  ON orders (created_at)
  WHERE status = 'pending';

The index is smaller and cheaper to maintain, and the planner uses it for queries whose WHERE clause implies status = 'pending'.

Covering indexes

A covering index includes all the columns a query needs, allowing an index-only scan that avoids visiting the table. PostgreSQL's INCLUDE clause adds non-key columns:

CREATE INDEX orders_customer_created_cover_idx
  ON orders (customer_id, created_at DESC)
  INCLUDE (total_cents);

Index-only scans work best on well-vacuumed tables.

Build indexes safely in production

A plain CREATE INDEX blocks writes to the table while it builds. On a live system, use:

CREATE INDEX CONCURRENTLY orders_customer_created_idx
  ON orders (customer_id, created_at DESC);

It's slower and can't run inside a transaction block, but doesn't block traffic. Periodically check for unused indexes in pg_stat_user_indexes and drop the ones that only cost you writes.

Reading EXPLAIN and EXPLAIN ANALYZE

EXPLAIN shows the planned execution. EXPLAIN ANALYZE actually runs the query, so wrap data-changing statements in a transaction and roll back.

EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

What to look for:

  • Scan types. Seq Scan on a large table for a selective query usually means a missing or unusable index. Index Scan and Index Only Scan are typically what you want for selective lookups. A sequential scan is fine for small tables or queries that read most rows.
  • Estimated vs actual rows. Large mismatches suggest stale statistics; run ANALYZE on the table.
  • Where time is spent. Each node shows actual time and loop count. Multiply per-loop time by loops to find the real cost of nested operations.
  • Sorts spilling to disk. "Sort Method: external merge" means the sort exceeded work_mem. An index matching the ORDER BY often removes the sort.

To find which queries matter, enable the pg_stat_statements extension. It aggregates calls and total time per query shape, so you can focus on what costs the most overall.

The N+1 Query Problem and ORMs

ORMs like Prisma, Drizzle, TypeORM, Sequelize, Django ORM, and Eloquent make development faster, but they make it easy to write code that issues one query for a list and then one more query per item:

// N+1: one query for orders, then one per order for its customer
const orders = await db.order.findMany({ take: 50 });
for (const order of orders) {
  order.customer = await db.customer.findUnique({
    where: { id: order.customerId },
  });
}

Fifty orders become fifty-one round trips. Load related data in bulk instead, with the ORM's eager loading (include, with, select_related) or a single join.

Log SQL in development to see what's actually sent, select only the columns you need, and use raw SQL for complex reporting queries.

If you're building the API layer as well, our Node.js and Express API guide covers how these query patterns fit into endpoint design.

Pagination: Keyset vs Offset

LIMIT 20 OFFSET 10000 looks harmless, but the database still has to read and discard the first 10,000 rows. Deep pages get progressively slower, and if rows are inserted between requests, users can see duplicates or miss items.

Keyset pagination (also called cursor pagination) remembers where the last page ended and continues from there:

-- First page
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- Next page: pass the last row's created_at and id as the cursor
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = 42
  AND (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The id tiebreaker keeps ordering stable when timestamps collide; support it with an index on (customer_id, created_at DESC, id DESC). You can't jump straight to page 37, which feeds and APIs rarely need. Offset pagination is still fine for small admin tables.

Connection Pooling

Each PostgreSQL connection is a separate server process, so thousands of direct connections become a problem, especially with serverless functions or many app instances.

  • Application-side pools (such as the pool in node-postgres) reuse connections within a single process.
  • PgBouncer sits between your app and the database and multiplexes many client connections onto a smaller number of server connections. In transaction mode, a server connection is assigned only for the duration of a transaction, which is efficient but breaks session-level features like SET without LOCAL, advisory session locks, and LISTEN. Recent PgBouncer versions support protocol-level prepared statements in transaction mode via max_prepared_statements.

Size pools conservatively; too many active connections increase contention, not throughput.

Caching

The fastest query is the one you don't run. Common layers:

  • HTTP and CDN caching for public, rarely changing responses.
  • Redis or Valkey with cache-aside: check the cache, fall back to the database, store the result with a TTL.
  • Materialized views for expensive aggregates that can tolerate staleness.

Prefer short TTLs plus explicit invalidation on writes, use namespaced keys like customer:42:summary, and guard against stampedes on popular keys with locks or slightly randomized TTLs. Never put user-private data under a shared key.

Scaling: Read Replicas and Partitioning

Read replicas

Replicas can absorb read-heavy traffic like reports and public pages. Replication is usually asynchronous, so replicas can lag. Route reads that must reflect a user's own recent write, such as "show my order right after checkout," to the primary.

Partitioning

Declarative partitioning splits a large table into smaller physical pieces, commonly by time:

CREATE TABLE events (
  id          bigint GENERATED ALWAYS AS IDENTITY,
  occurred_at timestamptz NOT NULL,
  payload     jsonb NOT NULL,
  PRIMARY KEY (id, occurred_at)
) PARTITION BY RANGE (occurred_at);

CREATE TABLE events_2026_11 PARTITION OF events
  FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');

You get partition pruning for time-bounded queries and cheap retention (dropping a partition beats a huge DELETE). Primary keys and unique constraints must include the partition key. Partitioning adds complexity, so use it for very large tables whose queries filter on the partition key. Before any of this, exhaust simpler options: better indexes, fixed N+1 queries, caching, and a larger instance.

Migrations

Schema changes should be versioned, reviewed, and applied automatically with tools like Prisma Migrate, Drizzle Kit, or Flyway. For zero-downtime changes on live tables:

  • Expand, then contract. Add the new column or table, deploy code that writes to both, backfill, switch reads, then remove the old structure in a later release.
  • Backfill in batches rather than one giant UPDATE that holds locks and bloats the table.
  • Add constraints without long locks. Add a foreign key or check constraint as NOT VALID, then run VALIDATE CONSTRAINT separately.
  • Set a lock_timeout (for example SET lock_timeout = '5s';) so a blocked ALTER TABLE fails fast instead of queuing behind a long transaction and stalling traffic.

Backups and Point-in-Time Recovery

A backup you haven't restored is a hope, not a plan.

  • Logical backups (pg_dump) are portable but slow to restore at scale.
  • Physical backups plus WAL archiving enable point-in-time recovery (PITR): restore a base backup, then replay the write-ahead log up to a moment just before an accidental DELETE or bad deploy. Tools like pgBackRest and WAL-G handle this, and most managed PostgreSQL services offer PITR within a retention window.
  • Store backups off-site, encrypted, and test restores regularly so you know your real recovery time.
  • Replicas are not backups. A mistaken DROP TABLE replicates too.

Next Steps

Database performance comes mostly from fundamentals: a normalized schema with real constraints, indexes that match real queries, plans you've actually read, and pagination, pooling, and caching that fit your traffic. Replicas and partitioning matter at scale; tested backups matter from day one.

If you're planning a new application or your existing one is slowing down, our React and Node.js development team can help with schema design, query tuning, and architecture. You can also read how we approach SaaS projects or request a quote.

DLN Web Studio

Author

Related Articles

Continue exploring our latest insights

Why Every Business Needs a Professional Website in 2025: The Ultimate Guide to Digital Success
Business Growth
2025-03-10
8 min read

Why Every Business Needs a Professional Website in 2025: The Ultimate Guide to Digital Success

Discover why having a professional website is crucial for business success in 2025. Learn from DLN Web Studio, the leading web design agency, about digital transformation and online presence strategies.

DLN Web Studio
Read
Web Development Trends 2025: What's Shaping the Future of Digital Innovation
Technology
2025-02-17
8 min read

Web Development Trends 2025: What's Shaping the Future of Digital Innovation

Explore the cutting-edge web development trends of 2025, from AI integration to performance optimization. Stay ahead with insights from expert developers.

DLN Web Studio
Read
Choosing the Right Web Design Agency: A Complete Guide for Business Owners
Business Strategy
2025-01-27
9 min read

Choosing the Right Web Design Agency: A Complete Guide for Business Owners

Learn how to select the perfect web design agency for your business. Expert tips on evaluating portfolios, understanding pricing, and ensuring project success.

DLN Web Studio
Read

Stay Updated

Get the latest insights on web development, digital strategy, and business growth delivered to your inbox.