How to Choose a Database: SQL vs NoSQL vs NewSQL vs Edge
Choose the right database across SQL, NoSQL, NewSQL, and edge options: the trade-offs of each category, selection criteria, and a decision framework.
Choosing a database whose data model does not fit the workload forces expensive migrations later. Picture an order system that stores one document per customer, with every order embedded in it. The customer page needs one read. A finance report of revenue per product across all customers has to unwind every customer document in a multi-stage aggregation. The mismatch between data model and access pattern is the root cause, not the engine’s speed. SQL, NoSQL, NewSQL, and edge database categories each carry concrete trade-offs that point to the right choice before the first migration becomes necessary.
For most projects the default is PostgreSQL, with Redis in front of it for the access patterns PostgreSQL handles poorly. Every other category below earns its place only when a specific requirement rules that pair out: a write volume no single primary absorbs, a residency rule that pins rows to a region, a time-series ingest rate, or a client that has to work offline. The decision tree at the end turns those four triggers into questions.
The Cost of the Wrong Choice#
Technical Debt Explosion: Switching databases mid-project touches every layer that reads or writes data. Using MySQL for time-series data creates query complexity with excessive date functions and subqueries. Moving to a specialized store like InfluxDB means rewriting the query layer, the retention logic, and every dashboard built on top of them.
Team Productivity Impact: Your choice directly affects development velocity. A team fluent in SQL that inherits MongoDB document queries spends months relearning how to model, index, and debug reads. NoSQL experts forced into rigid SQL schemas tend to over-engineer simple problems in the other direction.
Hidden Operational Costs:
- Self-hosted PostgreSQL: smallest invoice, largest share of engineer time (patching, vacuum tuning, failover drills)
- Managed PostgreSQL (RDS, Cloud SQL, Neon): larger invoice, most of that operational time handed to the provider
- DynamoDB: usage-based invoice and almost no administration, provided the access patterns were designed up front
Classical Database Categories#
Relational (SQL) Databases#
PostgreSQL#
PostgreSQL is an excellent default choice for most projects. It’s boring in the best possible way: reliable, well-documented, and graceful about edge cases. Recent major releases keep improving performance and extending SQL/JSON standard support, so the JSON gap that once pushed teams toward a document store has mostly closed.
When PostgreSQL Shines:
- Complex business logic requiring ACID transactions
- Analytics workloads with sophisticated queries
- Applications needing both relational and document storage (JSONB)
- Teams comfortable with SQL
Where JSONB Pays Off: Teams that move a relational app to PostgreSQL for its JSON support usually do it to delete a second datastore. Storing flexible metadata next to relational columns removes the document store from the diagram.
// PostgreSQL with JSONB - best of both worlds
const user = await db.query(`
SELECT id, email,
preferences->>'theme' as theme,
preferences->'notifications'->>'email' as email_notifications
FROM users
WHERE preferences @> '{"beta_features": true}'
`);
Gotchas:
- Write amplification with frequent updates (use HOT updates wisely)
- Connection management: use pgBouncer in production
- Vacuum tuning required for high-write workloads
MySQL#
MySQL earned its reputation powering the web’s biggest sites. It’s fast, well-understood, and has an ecosystem built around web applications.
MySQL works well for read-heavy web applications, for teams already running primary-replica replication or existing MySQL expertise, and for cost-conscious projects that lean on its community support.
Read Scaling in Practice: MySQL scales reads by adding replicas and treating them like a cache tier: denormalized data, aggressive indexing, and strategic partitioning. The throughput ceiling depends far more on row size and index fit than on the engine.
-- MySQL optimized for read performance
CREATE TABLE user_stats (
user_id INT PRIMARY KEY,
total_orders INT DEFAULT 0,
last_order_date DATE,
lifetime_value DECIMAL(10,2),
INDEX idx_lifetime_value (lifetime_value DESC),
INDEX idx_last_order (last_order_date)
) ENGINE=InnoDB;
The trade-offs show up over time: a less sophisticated query planner than PostgreSQL, JSON support that feels bolted-on, and replication lag that can turn tricky in multi-master setups.
SQLite#
Don’t underestimate SQLite. It now runs far beyond mobile apps, and with proper configuration it handles surprising workloads: edge applications with local data requirements, development and testing environments, applications with less than 100GB of data and modest concurrency, and embedded systems or IoT devices.
Performance Reality Check: reads are ordinary file reads served from page cache, which is why a single node goes further than most people expect. Concurrent writes are the real constraint: even in WAL mode, one writer holds the database at a time while readers continue uninterrupted.
// better-sqlite3: WAL mode for concurrent readers
import Database from 'better-sqlite3';
const db = new Database('app.db');
db.pragma('journal_mode = WAL');
db.pragma('synchronous = NORMAL'); // no corruption with WAL, but see the durability note below
db.pragma('cache_size = -64000'); // negative value means KiB, so 64MB
db.pragma('temp_store = MEMORY');
synchronous = NORMAL trades durability for fewer fsyncs. In WAL mode it never corrupts the database, but a transaction committed just before a power loss or OS crash can roll back on restart. An application crash loses nothing. Keep synchronous = FULL when every acknowledged commit must survive a power cut.
NoSQL Databases#
MongoDB#
MongoDB gets a lot of hate, often deserved, but it genuinely excels in specific scenarios: rapid prototyping with evolving schemas, content management systems, catalog systems with varied product attributes, and applications where the document structure already matches the business logic. Understanding those strengths and designing around the limitations is what makes it work.
Important Consideration: Always design your indexes first. Without them, MongoDB’s real-world performance falls far short of its specs.
// MongoDB indexing strategy for e-commerce
db.products.createIndex({
"category": 1,
"price": 1,
"createdAt": -1
});
// Compound index for faceted search
db.products.createIndex({
"category": 1,
"attributes.brand": 1,
"attributes.color": 1,
"price": 1
});
Production Gotchas:
- Memory usage grows with working set size
- Aggregation pipelines can be memory-intensive
- Sharding requires careful planning of shard keys
Redis#
Redis is a data structure server that happens to be very good at caching. The other structures solve coordination problems that SQL handles awkwardly.
Redis Use Cases Beyond Caching:
- Session storage with automatic expiration
- Rate limiting with sliding windows
- Real-time leaderboards and counters
- Pub/sub for real-time features
- Distributed locks for coordination
Common Pattern: distributed rate limiting shared across services. The check and the insert have to run as one step. A pipeline only batches commands, and other clients’ commands can run between them, so two servers can both see room for one more request. A Lua script runs atomically: Redis blocks other commands until it finishes.
// Sliding-window rate limiter: check and record in one atomic Lua script
import Redis from 'ioredis';
import { randomUUID } from 'node:crypto';
const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379');
const SLIDING_WINDOW = `
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)
if redis.call('ZCARD', key) >= limit then
return 0 -- rejected requests are not recorded
end
redis.call('ZADD', key, now, ARGV[4])
redis.call('PEXPIRE', key, window)
return 1
`;
export async function checkRateLimit(userId: string, limit: number, windowMs: number): Promise<boolean> {
const now = Date.now();
const allowed = await redis.eval(
SLIDING_WINDOW,
1, // one key, the rest go to ARGV
`rate_limit:${userId}`,
now,
windowMs,
limit,
`${now}-${randomUUID()}`, // unique member: same-millisecond requests stay distinct
);
return allowed === 1;
}
Two details carry the correctness. The sorted-set member is unique per request, so requests that arrive in the same millisecond do not overwrite each other. Only accepted requests enter the set, so a client over the limit gets through again as soon as old entries leave the window.
DynamoDB#
DynamoDB’s performance depends entirely on how well its data model fits your access patterns, but the appeal is real: true serverless with pay-per-use pricing, predictable single-digit millisecond latency, automatic scaling and backup, and global tables for multi-region applications.
The DynamoDB Mental Model: the table is shaped by the queries it has to answer. List every access pattern before you create the table, because adding one afterwards usually costs a new GSI or a full backfill.
// DynamoDB single-table design pattern
interface GameRecord {
PK: string; // USER#123 or GAME#456
SK: string; // PROFILE or SCORE#2024-01-15
Type: string; // USER or GAME or SCORE
GSI1PK?: string; // For secondary access patterns
GSI1SK?: string;
// ... other attributes
}
// Query user's recent scores (AWS SDK v3)
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb';
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const { Items } = await docClient.send(new QueryCommand({
TableName: 'GameData',
KeyConditionExpression: 'PK = :pk AND begins_with(SK, :sk)',
ExpressionAttributeValues: {
':pk': 'USER#123',
':sk': 'SCORE#'
},
ScanIndexForward: false, // Latest first
Limit: 10
}));
The gotchas are real too: hot partitions can throttle the entire application, query patterns must be known upfront, complex relationships require careful GSI design, and FilterExpressions still consume read capacity.
NewSQL: Best of Both Worlds#
CockroachDB#
CockroachDB promises PostgreSQL compatibility with global distribution. In practice it delivers on most of that, with some important caveats: the wire protocol is PostgreSQL’s, but the execution model underneath is a distributed consensus layer, and that shows up in latency and in the feature gaps.
When CockroachDB Makes Sense:
- Global applications requiring strong consistency
- Financial systems needing ACID across regions
- Applications outgrowing single-node PostgreSQL
- Teams wanting SQL with automatic sharding
Implementation Example: CockroachDB works well for fintech applications spanning multiple regions. Its multi-region SQL gives each table a locality. A REGIONAL BY ROW table homes every row in one region, and transactions stay strongly consistent across all of them.
-- CockroachDB multi-region SQL. Region names must match
-- the region values in the nodes' --locality flags.
ALTER DATABASE app SET PRIMARY REGION "us-east1";
ALTER DATABASE app ADD REGION "europe-west1";
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email STRING NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (email) -- unique across all regions
) LOCALITY REGIONAL BY ROW;
A hidden crdb_region column holds each row’s home region. By default it is the region of the gateway node that inserted the row, and the application can set it explicitly. Every index on the table, the email index included, is partitioned by crdb_region, so an email is stored with its row. Because crdb_region is not part of the UNIQUE definition, uniqueness is global: each insert checks the other regions before it commits, which adds cross-region latency. UNIQUE (crdb_region, email) makes the email unique per region and removes that check. The id column needs no check, because CockroachDB skips uniqueness checks for gen_random_uuid() values by default.
The trade-offs: higher latency than single-node databases because of consensus, a higher price tag than traditional PostgreSQL, and some PostgreSQL features that are still missing or behave differently.
Edge Database Solutions#
PouchDB/CouchDB#
For applications that need to work offline, CouchDB’s replication model is still the reference design, and PouchDB brings the same protocol to the browser: field service applications, mobile apps in areas with poor connectivity, and collaborative applications that can tolerate eventual consistency.
Implementation Pattern:
// PouchDB offline-first pattern
const localDB = new PouchDB('local-data');
const remoteDB = new PouchDB('https://server.com/data');
// Two-way sync with conflict resolution
const sync = localDB.sync(remoteDB, {
live: true,
retry: true
}).on('change', (info) => {
console.log('Sync change:', info);
}).on('error', (err) => {
console.log('Sync error:', err);
});
// App works offline, syncs when online
await localDB.put({
_id: 'user-123',
name: 'John Doe',
lastModified: new Date().toISOString()
});
InfluxDB#
When you’re dealing with metrics, logs, or IoT data, specialized time-series databases like InfluxDB outperform general-purpose engines on ingest rate, storage footprint, and range queries.
InfluxDB brings automatic downsampling and retention policies, built-in time-based functions and aggregations, efficient storage for time-series data, and native integration with monitoring tools.
-- InfluxQL query for system metrics
SELECT mean("cpu_usage")
FROM "system_metrics"
WHERE time >= now() - 24h
GROUP BY time(1h), "host"
Database Selection Matrix#
By Use Case#
E-commerce Platform:
- Catalog: PostgreSQL (structured product data + JSONB for attributes)
- Sessions: Redis (fast access + automatic expiration)
- Orders: PostgreSQL (ACID compliance for financial data)
- Analytics: ClickHouse or BigQuery (analytical workloads)
IoT Application:
- Device State: Redis (real-time updates)
- Time Series: InfluxDB (sensor data)
- Configuration: PostgreSQL (device management)
- Edge Cache: SQLite (local device storage)
Social Media App:
- User Profiles: PostgreSQL (relational data)
- Posts/Timeline: DynamoDB (high scale, simple queries)
- Real-time: Redis Streams (notifications, chat)
- Search: Elasticsearch (content discovery)
By Workload Limits#
User counts are a poor proxy for scale: a million users who read once a day load a database less than a thousand devices that write every second. The thresholds that matter are the peak write rate against what one primary sustains, and the working set against RAM. Measure the first with a load test on your instance class (pgbench with a custom script that mimics your writes); estimate the second from the capacity model further down.
One primary absorbs the write peak and the working set fits in RAM: PostgreSQL + Redis. Simple, well-understood, cost-effective.
Reads or the working set outgrow one node, writes still fit:
- Read replicas for PostgreSQL
- A larger memory class, or table partitioning that keeps the hot partitions small, when the working set outgrows RAM
- Redis for hot keys and sessions
- Elasticsearch for search
The write peak approaches what one primary sustains, even after batching and tuning:
- DynamoDB with careful partition design, when every access pattern is known up front
- Sharded PostgreSQL or CockroachDB, when writes still need joins or transactions across many rows
- Redis Cluster for caching
- Specialized databases for specific workloads
Migration Scenarios#
MongoDB to PostgreSQL#
The Problem: Content management systems using MongoDB can struggle with complex queries. Aggregation pipelines become unmaintainable, and the lack of schema validation causes data quality issues.
The Solution: move to PostgreSQL with JSONB columns for the flexible parts of the content, keeping the benefits of document storage while gaining SQL’s query power.
The Cutover: application-level dual writes look simple, but the second write can fail after the first one commits. If that failure is only logged, the second store drifts silently and is incomplete on the day you need it for a rollback. A safer cutover keeps one system of record at a time and copies its changes one way, through change data capture (CDC):
- Backfill: open a change stream on MongoDB and store its resume token, then copy the existing documents into PostgreSQL. Replaying from the token afterwards catches every write that landed during the copy.
- Replicate: a consumer applies each change to PostgreSQL as an idempotent upsert and parks failures in a table instead of dropping them. Debezium’s MongoDB connector does the same job on top of change streams if you already run Kafka.
- Reconcile: a scheduled job compares row counts and per-document hashes between the two stores and re-queues mismatches.
- Shadow reads: MongoDB still answers every request; PostgreSQL is read in the background and every difference is logged.
- Flip: once mismatches stay at zero, move reads to PostgreSQL, then make it the system of record for writes. Reverse the pipe (Debezium’s PostgreSQL connector reads PostgreSQL’s logical decoding) so MongoDB stays complete until the rollback window closes.
// MongoDB stays the system of record; a change stream copies
// every committed change into PostgreSQL.
import { MongoClient, type ChangeStreamDocument, type ResumeToken } from 'mongodb';
import { Pool } from 'pg';
interface MongoPost {
_id: string;
title: string;
body: string;
tags: string[];
}
const mongo = new MongoClient(process.env.MONGO_URL ?? 'mongodb://localhost:27017');
const posts = mongo.db('cms').collection<MongoPost>('posts');
const pg = new Pool({ connectionString: process.env.DATABASE_URL });
async function applyChange(change: ChangeStreamDocument<MongoPost>): Promise<void> {
switch (change.operationType) {
case 'insert':
case 'update':
case 'replace': {
const doc = change.fullDocument;
if (!doc) return; // deleted before the lookup ran; its delete event follows
const { _id, ...content } = doc;
// Idempotent upsert: replaying an event after a restart is harmless
await pg.query(
`INSERT INTO posts (id, doc) VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE SET doc = EXCLUDED.doc`,
[_id, content],
);
return;
}
case 'delete':
await pg.query('DELETE FROM posts WHERE id = $1', [change.documentKey._id]);
return;
default:
// drop, rename, invalidate: park it and decide by hand
throw new Error(`unexpected change: ${change.operationType}`);
}
}
export async function replicate(resumeAfter?: ResumeToken): Promise<void> {
const stream = posts.watch([], { fullDocument: 'updateLookup', resumeAfter });
for await (const change of stream) {
try {
await applyChange(change);
} catch (error) {
// Never swallow a failed apply: park it for the retry worker
await pg.query('INSERT INTO sync_failures (event, error) VALUES ($1, $2)', [
JSON.stringify(change),
String(error),
]);
}
await pg.query("UPDATE sync_checkpoint SET resume_token = $1 WHERE stream = 'posts'", [
JSON.stringify(change._id),
]);
}
}
// Shadow read: MongoDB still answers, PostgreSQL is read and compared
export async function getPost(id: string): Promise<MongoPost | null> {
const primary = await posts.findOne({ _id: id });
void pg
.query<{ doc: Omit<MongoPost, '_id'> }>('SELECT doc FROM posts WHERE id = $1', [id])
.then(({ rows }) => {
if (!sameContent(primary, rows[0]?.doc)) console.warn('shadow_read_mismatch', { id });
})
.catch((error: unknown) => console.warn('shadow_read_failed', { id, error }));
return primary;
}
function sameContent(a: MongoPost | null, b: Omit<MongoPost, '_id'> | undefined): boolean {
if (!a || !b) return !a && !b;
return a.title === b.title && a.body === b.body && JSON.stringify(a.tags) === JSON.stringify(b.tags);
}
Change streams need a replica set or a sharded cluster, and resuming from a stored token works only while the oplog still holds that point. Size the oplog for the longest consumer outage you plan to survive.
Outcomes:
- Schema validation and constraints move data-quality checks out of application code
- Multi-entity reads become joins instead of hand-written aggregation stages
- One engine to back up, monitor, and tune instead of two
Single-Region to Multi-Region#
The Challenge: Growing SaaS applications need to expand from single-region to global, requiring data residency compliance and low latency worldwide.
The Solution: Migrating from a single PostgreSQL to CockroachDB multi-region SQL homes each user’s rows in their own region, keeps small reference tables readable everywhere, and still gives billing and analytics one strongly consistent database to query.
Implementation (continuing with the regions declared above):
-- User data: each row lives in its home region
ALTER TABLE users SET LOCALITY REGIONAL BY ROW;
ALTER TABLE user_profiles SET LOCALITY REGIONAL BY ROW;
-- Keep every replica of EU-homed rows inside the EU,
-- including the non-voting replicas added by default
ALTER DATABASE app ADD SUPER REGION "europe" VALUES "europe-west1";
-- Read-mostly reference data that every region reads
ALTER TABLE plans SET LOCALITY GLOBAL;
Trade-offs:
- Reads go to the leaseholder of a row’s range by default. In a
REGIONAL BY ROWtable that leaseholder sits in the row’s home region, so a user reading their own rows from that region stays local, and a read from another region crosses to the home region. GLOBALtables serve strongly consistent reads from every region. The price is slower writes, because each write replicates to every region, so keep residency-bound data out of them.- Follower reads (
AS OF SYSTEM TIME follower_read_timestamp()) let the nearest replica answer any table, at the cost of data at least 4.2 seconds old. - Residency takes more than row placement. Non-voting replicas in other regions are on by default; super regions keep them inside a set of regions. Even then, indexed values can reach system ranges and logs, so treat the setup as necessary but not sufficient for compliance.
- Uniqueness checks on global
UNIQUEcolumns and every write to aGLOBALtable cross regions, and the cluster costs more to run.
Performance Characteristics#
Read Performance#
Point-lookup throughput tracks the storage medium more than the engine name. In-memory Redis sits at the top, managed key-value stores such as DynamoDB come next, and indexed relational or document engines follow. The gaps narrow sharply once the working set fits in page cache, which is why published numbers rarely transfer between deployments. Measure with your own record size, index shape, and concurrency before treating any ordering as fixed.
Complex Queries (analytical workloads):
- PostgreSQL: Excellent (sophisticated query planner)
- CockroachDB: Good (distributed but still SQL)
- MongoDB: Workable (the aggregation pipeline joins collections with
$lookup, but a model built around embedded documents needs extra stages for cross-entity reports) - DynamoDB: Not applicable (limited query capabilities)
Write Performance Under Load#
Concurrent Writes:
- DynamoDB: Scales automatically, consistent performance until a partition goes hot
- Redis: Excellent until memory limit
- PostgreSQL: Good with proper connection pooling
- MongoDB: Good across documents (WiredTiger uses document-level concurrency control, so clients modify different documents at the same time); concurrent writes to one hot document contend, and sharding spreads load only as well as the shard key does
Implementation Patterns#
Database Sharding Strategies#
Horizontal Sharding (dividing data across servers):
// User-based sharding
import { createHash } from 'node:crypto';
import { Pool } from 'pg';
const NUM_SHARDS = 4;
function getShardForUser(userId: string): number {
const hash = createHash('md5').update(userId).digest('hex');
return parseInt(hash.substring(0, 8), 16) % NUM_SHARDS;
}
// Route queries to the shard that owns the user
class ShardedUserService {
// One pool per shard; the array index is the shard number
constructor(private readonly shards: Pool[]) {}
async getUser(userId: string) {
const shard = this.shards[getShardForUser(userId)];
const { rows } = await shard.query('SELECT * FROM users WHERE id = $1', [userId]);
return rows[0];
}
}
Vertical Sharding (separating by feature):
// Separate databases by domain
import { Pool } from 'pg';
class UserService {
private readonly profiles = new Pool({ connectionString: process.env.PROFILES_DB_URL });
private readonly preferences = new Pool({ connectionString: process.env.PREFERENCES_DB_URL });
private readonly analytics = new Pool({ connectionString: process.env.ANALYTICS_DB_URL });
async getFullUser(userId: string) {
const [profile, preferences, analytics] = await Promise.all([
this.profiles.query('SELECT * FROM profiles WHERE user_id = $1', [userId]),
this.preferences.query('SELECT * FROM preferences WHERE user_id = $1', [userId]),
this.analytics.query('SELECT * FROM user_stats WHERE user_id = $1', [userId]),
]);
return { ...profile.rows[0], preferences: preferences.rows[0], analytics: analytics.rows[0] };
}
}
Connection Management#
PostgreSQL Connection Pooling:
// Production PostgreSQL setup
import { Pool } from 'pg';
const pool = new Pool({
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
// Critical production settings
max: 20, // Maximum connections
idleTimeoutMillis: 30000, // Close idle connections
connectionTimeoutMillis: 2000, // Fail fast on connection issues
maxUses: 7500, // Rotate connections to prevent memory leaks
});
// Always use transactions for data consistency
async function transferMoney(fromUserId: string, toUserId: string, amount: number) {
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(
'UPDATE accounts SET balance = balance - $1 WHERE user_id = $2',
[amount, fromUserId]
);
await client.query(
'UPDATE accounts SET balance = balance + $1 WHERE user_id = $2',
[amount, toUserId]
);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
Monitoring and Troubleshooting#
Key Metrics to Track#
PostgreSQL Essential Metrics:
- Connection usage (
pg_stat_activity) - Query performance (
pg_stat_statements) - Index usage (
pg_stat_user_indexes) - Replication lag (
pg_stat_replication)
-- PostgreSQL health check queries
-- Long-running queries
SELECT pid, now() - query_start as duration, query
FROM pg_stat_activity
WHERE now() - query_start > interval '5 minutes';
-- Index usage statistics
SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch
FROM pg_stat_user_indexes
ORDER BY idx_scan DESC;
-- Connection count by state
SELECT state, count(*)
FROM pg_stat_activity
GROUP BY state;
DynamoDB CloudWatch Metrics:
- ConsumedReadCapacityUnits / ConsumedWriteCapacityUnits
- ThrottledRequests (critical!)
- SuccessfulRequestLatency
- SystemErrors
Note: DynamoDB pricing was reduced by ~50% in November 2024, making on-demand pricing more cost-effective for variable workloads.
MongoDB Key Metrics:
- Operations per second (opcounters)
- Working set size vs available memory
- Lock percentage
- Replication lag
Common Performance Issues#
The N+1 Query Problem:
// BAD: N+1 queries
async function getUsersWithPosts() {
const users = await db.query('SELECT * FROM users');
for (const user of users) {
user.posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
}
return users;
}
// GOOD: Single query with JOIN
async function getUsersWithPosts() {
return db.query(`
SELECT u.*, p.id as post_id, p.title, p.content
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
ORDER BY u.id, p.created_at DESC
`);
}
Connection Pool Exhaustion:
// Monitoring connection pool health
setInterval(() => {
console.log({
totalConnections: pool.totalCount,
idleConnections: pool.idleCount,
waitingClients: pool.waitingCount
});
if (pool.waitingCount > 5) {
console.warn('Connection pool under pressure!');
}
}, 30000);
Future-Proofing Your Database Choice#
Technology Trends to Watch#
Vector Databases for AI/ML: pgvector for PostgreSQL, Pinecone, Weaviate
- Embedding storage for semantic search
- RAG (Retrieval-Augmented Generation) applications
- Image and document similarity search
Multi-Model Databases: Azure Cosmos DB, SurrealDB
- Cosmos DB exposes one managed service through several APIs: NoSQL, MongoDB, Apache Cassandra, Apache Gremlin, and Table
- Azure Cosmos DB for PostgreSQL is a separate service on a retirement path: it accepts no new deployments, existing clusters stay supported, and Microsoft’s migration path leads to Azure Database for PostgreSQL elastic clusters
- SurrealDB stores documents, graph relations, vectors, and relational tables in one engine
- One engine to operate, at the cost of depending on a single vendor’s query surface
Serverless SQL: the managed options now cover both open-source engines and new distributed designs.
- Neon: PostgreSQL with compute decoupled from storage, autoscaling, scale-to-zero, and branching; now part of Databricks
- PlanetScale: managed Vitess (MySQL-compatible) and managed PostgreSQL clusters
- Turso: an SQLite-compatible engine with a managed cloud for Turso and libSQL databases, aimed at embedded and on-device use with sync to the cloud
- Aurora DSQL: AWS’s serverless, distributed, PostgreSQL-compatible database (generally available since May 2025), with active-active multi-Region clusters
Pick a hosted database by its exit path as much as its features. Fauna, a serverless transactional database with its own query language, shut its service down on May 30, 2025, and deleted customer accounts when it did. A provider that speaks a standard wire protocol (PostgreSQL, MySQL, SQLite) leaves a migration path that a proprietary query language does not.
Planning for Growth#
Capacity Planning Framework: project the two limits from the workload-limits section (write peak per primary, working set against RAM) from metrics you already collect. Every input below comes from production metrics or a load test; none of them is a universal constant.
// Capacity projection from workload metrics
interface WorkloadProjection {
currentUsers: number; // the population the per-user averages were measured on
monthlyGrowthRate: number; // fraction, e.g. 0.05 for 5% per month
writesPerUserPerDay: number; // from production metrics
readsPerUserPerDay: number;
peakToAverageRatio: number; // busiest second divided by the daily average
bytesPerUser: number; // table + index bytes divided by currentUsers
hotDataFraction: number; // share of the data touched in a typical hour
ramBytesPerNode: number;
measuredWritesPerSecPerPrimary: number; // from a load test on your instance class
}
const SECONDS_PER_DAY = 86_400;
const GIB = 1024 ** 3;
function projectDatabaseNeeds(p: WorkloadProjection, months: number) {
const users = p.currentUsers * Math.pow(1 + p.monthlyGrowthRate, months);
const peakWritesPerSec = ((users * p.writesPerUserPerDay) / SECONDS_PER_DAY) * p.peakToAverageRatio;
const peakReadsPerSec = ((users * p.readsPerUserPerDay) / SECONDS_PER_DAY) * p.peakToAverageRatio;
const dataBytes = users * p.bytesPerUser;
return {
users: Math.round(users),
peakWritesPerSec: Math.round(peakWritesPerSec),
peakReadsPerSec: Math.round(peakReadsPerSec),
dataSizeGiB: Math.round(dataBytes / GIB),
workingSetFitsInRam: dataBytes * p.hotDataFraction < p.ramBytesPerNode,
// Close to 1 means one primary no longer absorbs the write peak
primaryWriteUtilization: peakWritesPerSec / p.measuredWritesPerSecPerPrimary,
};
}
Per-day rates divided by 86,400 give an average per second; the peak factor turns that into the busiest second, which is the number a primary has to survive. When primaryWriteUtilization approaches 1 inside the planning horizon, the write branch of the decision tree below applies.
Decision Framework#
Walk the tree from the top and stop at the first leaf you reach; a “no” to the first four questions lands on the default.
Each leaf comes with the one sentence you can give a teammate:
| Leaf | Why |
|---|---|
| PostgreSQL + Redis | One primary absorbs the writes, so joins, constraints, and transactions come with no extra engine; JSONB holds document-shaped attributes and Redis takes sessions, counters, and rate limits. |
| DynamoDB with designed keys | Every access pattern is a key lookup known up front, and each transaction fits TransactWriteItems: up to 100 items in one account and Region. MongoDB fits the same branch when the domain is document-shaped and the team already runs it. |
| Distributed SQL or sharded PostgreSQL | Writes outgrow one primary but still need ad-hoc joins or multi-row transactions; CockroachDB and Aurora DSQL keep SQL semantics across nodes, while sharding keeps PostgreSQL and moves cross-shard queries into the application. |
| CockroachDB REGIONAL BY ROW | Residency is a placement rule, and REGIONAL BY ROW plus super regions write that rule into the schema. |
| Time-series store beside PostgreSQL | Retention, downsampling, and time-bucketed queries are built in, and the relational data stays in PostgreSQL. |
| PouchDB / CouchDB | The same replication protocol runs in the browser and on the server, so local writes sync when the connection returns. |
MongoDB runs multi-document ACID transactions, DynamoDB offers TransactWriteItems and strongly consistent reads, and CockroachDB keeps ACID across regions. The branches split on scope: how many entities or partitions one transaction touches, and whether the queries are known up front or written ad hoc.
Constraints Outside the Tree#
- Team expertise: a team that already runs one engine well pays less to stay on it
- Operational budget: managed services trade a larger invoice for less engineer time
- Full-text search: Elasticsearch beside the primary database, fed from it
- Latency below 10 ms on hot keys: Redis in front of whichever leaf you picked
- Compliance beyond residency: encryption, audit trails, and backup retention apply to every leaf
The PostgreSQL + Redis default holds until one of those answers forces a change: a write volume that no single primary absorbs, a residency rule that pins rows to a region, a time-series ingest rate that fills the disk, or a client that has to work offline. Each of those has a specialized answer above, and each one adds an engine to operate. Add the second engine once a requirement actually demands it.
References#
- PostgreSQL Documentation (opens in new tab) - Official reference for PostgreSQL, covering data types, indexing, transactions, and advanced features like JSONB and full-text search
- What is Amazon DynamoDB? (opens in new tab) - AWS guide to DynamoDB’s key-value and document model, capacity modes, and consistency options
- MongoDB Manual (opens in new tab) - Official MongoDB documentation covering the document data model, aggregation pipeline, and schema design patterns
- Redis Documentation (opens in new tab) - Official Redis reference for in-memory data structures, persistence options, pub/sub, and cluster configuration
- Choosing an AWS Database Service (opens in new tab) - AWS decision guide comparing relational, key-value, document, in-memory, and graph databases for different workload types
- MySQL 8.4 Reference Manual (opens in new tab) - Official MySQL documentation covering the storage engine model, replication, and query optimization
- Amazon DynamoDB Pricing (opens in new tab) - Current on-demand and provisioned throughput rates, including the reduced on-demand pricing referenced above
- better-sqlite3 API Documentation (opens in new tab) - Reference for the synchronous SQLite driver used in the examples, including the pragma helper and WAL configuration
- SQLite PRAGMA Statements (opens in new tab) - The
synchronouspragma, including why WAL withNORMALcannot corrupt the database but can roll back the last commits after a power loss - Redis: Scripting with Lua (opens in new tab) - How
EVALpasses keys and arguments, and the guarantee that a script runs atomically - MongoDB Transactions (opens in new tab) - Multi-document ACID transactions on replica sets and sharded clusters
- MongoDB $lookup (opens in new tab) - The aggregation stage that performs a left outer join to another collection
- MongoDB WiredTiger Storage Engine (opens in new tab) - Document-level concurrency control for write operations
- MongoDB Change Streams (opens in new tab) - Subscribing to collection changes, resume tokens,
updateLookup, and the replica set requirement - Debezium Connector for MongoDB (opens in new tab) - CDC connector that snapshots collections and then streams changes through change streams
- Debezium Connector for PostgreSQL (opens in new tab) - CDC connector built on PostgreSQL logical decoding, used to reverse the pipe after the flip
- pgbench (opens in new tab) - PostgreSQL’s benchmarking tool, with custom transaction scripts for measuring the write ceiling of one primary
- PostgreSQL Table Partitioning (opens in new tab) - How partitioning helps when heavily accessed rows sit in a few partitions, so the heavily used parts of the indexes are more likely to fit in memory
- Amazon DynamoDB Transactions (opens in new tab) -
TransactWriteItemslimits (100 items, one account and Region) and the strongly consistent read option - CockroachDB Table Localities (opens in new tab) -
REGIONAL BY ROW,REGIONAL BY TABLE, andGLOBALtables, and howcrdb_regionhomes each row - CockroachDB ALTER TABLE (opens in new tab) -
SET LOCALITYand how unique indexes onREGIONAL BY ROWtables enforce global or per-region uniqueness - CockroachDB SQL FAQs (opens in new tab) - Why uniqueness checks are skipped for
gen_random_uuid()and add latency onREGIONAL BY ROWtables - CockroachDB Follower Reads (opens in new tab) - Leaseholder reads by default, exact and bounded staleness reads, and strong reads from
GLOBALtables - CockroachDB Data Domiciling (opens in new tab) - Non-voting replicas, super regions, and the limits of keeping data inside a region
- CockroachDB ALTER DATABASE (opens in new tab) -
SET PRIMARY REGION,ADD REGION, andADD SUPER REGIONsyntax - Fauna Shuts Down (opens in new tab) - InfoQ report on the Fauna service ending on May 30, 2025, with accounts deleted at shutdown
- Azure Cosmos DB Documentation (opens in new tab) - The service’s NoSQL, MongoDB, Cassandra, Gremlin, and Table APIs
- Migrate to an Azure Database for PostgreSQL Elastic Cluster (opens in new tab) - Azure Cosmos DB for PostgreSQL blocks new deployments on its retirement path; the migration workflow to elastic clusters
- SurrealDB Documentation (opens in new tab) - A multi-model engine for documents, graphs, vectors, and relational tables
- Neon Documentation (opens in new tab) - PostgreSQL with decoupled compute and storage, autoscaling, scale-to-zero, and branching
- PlanetScale Documentation (opens in new tab) - Managed Vitess and PostgreSQL clusters
- Turso Documentation (opens in new tab) - SQLite-compatible embedded engine and the managed Turso Cloud for Turso and libSQL databases
- What is Amazon Aurora DSQL? (opens in new tab) - Serverless, distributed, PostgreSQL-compatible database with multi-Region clusters
- Amazon Aurora DSQL Is Now Generally Available (opens in new tab) - The May 27, 2025 general availability announcement
Related posts
A decision guide to key-value storage: where it fits, why Redis or Valkey is the default, and when etcd, DynamoDB, or an in-process cache is the better pick.
redis · dynamodb · caching +4
Event routing, idempotent delivery rows in PostgreSQL, quiet hours that defer delivery, and per-channel Redis rate limits for a multi-channel notification system
typescript · postgresql · architecture +4
Keep identity reads in DynamoDB, route sort, filters, facets, and full text to a zero-ETL OpenSearch read model, with a staging checklist and a PostgreSQL override.
dynamodb · aws · architecture +2
What Aurora Serverless v2 is under the hood: shared storage, ACU-driven compute, platform versions, the Caspian substrate, scale-to-zero, and mixed-mode clusters.
aws · data-storage-orm · architecture +1
A practical guide to multi-tier caching: in-memory, Redis, and CDN layers, cache-aside vs write-through, invalidation across tiers, and stampede prevention.
caching · redis · aws +4