Skip to content

What Is a Key-Value Store? Choosing the Right Solution

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.

Ayhan Sipahi Ayhan Sipahi

Applying relational database patterns to key-value access workloads (session storage, caching, cart data) causes avoidable latency and schema complexity. Choosing the wrong storage model forces teams into index-tuning cycles that cannot fix a fundamental architectural mismatch. Key-value storage removes the mismatch: the data model matches the access pattern, so a lookup costs one hash probe instead of a query plan.

For distributed workloads, Redis (or Valkey, its BSD-licensed drop-in replacement) is the default worth beating. The exceptions are narrow and predictable: etcd for configuration and coordination, DynamoDB for serverless traffic that swings, an in-process cache when there is only one server, and embedded Hazelcast when the whole deployment runs on the JVM.

The “Just Use a Database” Misconception#

The pattern is familiar. Session data lives in MySQL, user preferences live in a second table, and every request joins them to rebuild state that was never relational to begin with. Under demo load the response times climb, and the first instinct is to add indexes and widen the connection pool.

Those fixes buy a little headroom, then stall. The query planner is doing real work on every request: parse, plan, walk indexes, materialize a join. None of that work is required to answer “give me the value stored under this session id”.

The Key-Value Data Model#

Key-value storage is a NoSQL database paradigm that stores data as pairs of unique identifiers (keys) and their associated values. Unlike relational databases with predefined schemas and complex relationships, KV stores use a simple, flat structure optimized for fast retrieval.

// Basic Key-Value Concept
const keyValueStore = {
  "user:1001": {
    name: "John Doe",
    email: "john@example.com",
    lastLogin: "2024-01-15T10:30:00Z"
  },
  "session:abc123": {
    userId: 1001,
    expiresAt: 1642248600,
    permissions: ["read", "write"]
  },
  "cart:user:1001": [
    { productId: 501, quantity: 2 },
    { productId: 302, quantity: 1 }
  ]
};

// Access Pattern: O(1) lookup time
const userData = keyValueStore["user:1001"];
const sessionData = keyValueStore["session:abc123"];

Schema-Free by Design#

  • Schema-free: Values can be anything: strings, numbers, JSON objects, binary data, arrays
  • Simple Operations: Primary operations are GET, PUT, DELETE by key
  • Fast Access: Optimized for sub-millisecond key lookups using hash tables or B-trees
  • Flexible Values: Support for atomic operations on complex data types (lists, sets, hashes)

Here’s a data model comparison that illustrates the fundamental difference:

-- Relational Database (Complex)
SELECT u.name, u.email, s.permissions
FROM users u
JOIN sessions s ON u.id = s.user_id
WHERE s.session_id = 'abc123';

-- Key-Value Store (Simple)
GET session:abc123
GET user:1001

The relational approach requires the database to plan queries, maintain indexes, and execute joins. The key-value approach is a direct hash table lookup.

Common Access Patterns#

The five access patterns below cover most of what teams actually store in a KV system.

1. Session Management#

This is where the biggest wins typically occur. E-commerce session storage is perfect for key-value patterns:

// E-commerce session storage
interface UserSession {
  userId: string;
  cartItems: CartItem[];
  preferences: UserPreferences;
  expiresAt: number;
}

// Key pattern: session:${sessionId}
const sessionKey = "session:abc123-def456-ghi789";
await kvStore.set(sessionKey, sessionData, { ttl: 3600 }); // 1 hour expiry

The ttl option above expires the session automatically once the hour elapses.

2. Caching Layer#

Database query result caching is one of the most common use cases for KV storage:

# Database query result caching
import json

import redis

redis_client = redis.Redis(decode_responses=True)


def get_user_profile(user_id: int) -> dict | None:
    cache_key = f"user_profile:{user_id}"
    cached = redis_client.get(cache_key)
    if cached is not None:
        return json.loads(cached)

    # Name the columns: SELECT * would copy fields such as password_hash into the cache
    row = database.fetch_one(
        "SELECT id, display_name, avatar_url, updated_at FROM users WHERE id = %s",
        (user_id,),
    )
    if row is None:
        return None

    profile = {
        "id": row["id"],
        "display_name": row["display_name"],
        "avatar_url": row["avatar_url"],
        "updated_at": row["updated_at"].isoformat(),  # datetime is not JSON-serializable
    }
    redis_client.set(cache_key, json.dumps(profile), ex=300)  # 5 min cache
    return profile

The five-minute TTL bounds how stale that cached profile can get. The explicit column list keeps secrets out of the cache, and the isoformat() call turns the timestamp into a string that json.dumps accepts.

3. Real-time Analytics and Counters#

For systems that need atomic operations on counters:

// Real-time page view counting
public class PageViewCounter {
    private IMap<String, Long> pageViews;

    public void incrementPageView(String pageId) {
        String key = "pageviews:" + pageId;
        pageViews.merge(key, 1L, Long::sum);  // Atomic increment
    }

    public long getPageViews(String pageId) {
        return pageViews.getOrDefault("pageviews:" + pageId, 0L);
    }
}

The atomic merge above avoids the lost-update race that a separate read-modify-write would introduce.

4. Configuration Management#

etcd’s watch semantics make it a natural fit for dynamic application configuration:

// Dynamic application configuration
type ConfigManager struct {
    client *clientv3.Client
}

// Watch loads the current config, then calls onChange for every update
// until ctx is cancelled.
func (c *ConfigManager) Watch(ctx context.Context, service string, onChange func(*Config)) error {
    key := fmt.Sprintf("/config/%s", service)

    resp, err := c.client.Get(ctx, key)
    if err != nil {
        return err
    }
    if len(resp.Kvs) == 0 {
        return fmt.Errorf("config %q not found", key)
    }
    config, err := decode(key, resp.Kvs[0].Value)
    if err != nil {
        return err
    }
    onChange(config)

    // Start right after the revision we read, so no update falls in between
    watchCh := c.client.Watch(ctx, key, clientv3.WithRev(resp.Header.Revision+1))
    for wresp := range watchCh {
        if err := wresp.Err(); err != nil {
            return err
        }
        for _, ev := range wresp.Events {
            if ev.Type != clientv3.EventTypePut {
                continue // ignore deletes, keep the last good config
            }
            config, err := decode(key, ev.Kv.Value)
            if err != nil {
                return err
            }
            onChange(config)
        }
    }
    return ctx.Err()
}

func decode(key string, raw []byte) (*Config, error) {
    var config Config
    if err := json.Unmarshal(raw, &config); err != nil {
        return nil, fmt.Errorf("decode %q: %w", key, err)
    }
    return &config, nil
}

A missing key returns an error instead of indexing an empty Kvs slice, and a malformed value fails loudly instead of yielding an empty config. The watch starts at the revision after the initial read, so an update that lands between Get and Watch still arrives.

5. Multi-Tier Caching Strategy#

Here’s a hybrid approach that combines the benefits of different storage tiers:

import { LRUCache } from "lru-cache";
import Redis from "ioredis";

// L1: in-process LRU (fastest, bounded, per instance)
// L2: Redis (shared by every instance)
// L3: the database (source of truth)

const INVALIDATION_CHANNEL = "cache:invalidate";
const NOT_FOUND = { found: false } as const;
type L1Entry<T> = { found: true; value: T } | typeof NOT_FOUND;

export class MultiTierCache<T> {
  private readonly l1 = new LRUCache<string, L1Entry<T>>({
    max: 10_000, // entry count, not bytes
    ttl: 60_000, // 1 min: the backstop when an invalidation message is lost
  });

  constructor(
    private readonly redis: Redis,
    subscriber: Redis, // pub/sub needs its own connection
    private readonly load: (key: string) => Promise<T | null>, // null = not found
  ) {
    void subscriber.subscribe(INVALIDATION_CHANNEL);
    subscriber.on("message", (_channel, key) => {
      this.l1.delete(key);
    });
  }

  async get(key: string): Promise<T | null> {
    const local = this.l1.get(key);
    if (local !== undefined) return local.found ? local.value : null;

    const cached = await this.redis.get(key);
    if (cached !== null) {
      const parsed = JSON.parse(cached) as T | null; // "null" is a cached miss
      this.remember(key, parsed);
      return parsed;
    }

    const value = await this.load(key);
    // Cache misses too (shorter TTL), so unknown keys stop reaching the database
    await this.redis.set(key, JSON.stringify(value), "EX", value === null ? 30 : 300);
    this.remember(key, value);
    return value;
  }

  private remember(key: string, value: T | null): void {
    // A miss gets the same 30 s in L1 as in Redis, so a new key shows up within 30 s
    if (value === null) this.l1.set(key, NOT_FOUND, { ttl: 30_000 });
    else this.l1.set(key, { found: true, value });
  }

  // Call after the database write commits
  async invalidate(key: string): Promise<void> {
    await this.redis.del(key);
    await this.redis.publish(INVALIDATION_CHANNEL, key);
  }
}

L1 stores the parsed value, so a hit returns the same type from either tier. The checks compare against undefined and null, so cached values such as 0, "" or false still count as hits. A miss is cached too, for 30 seconds in both tiers, so a flood of requests for keys that do not exist stops at Redis instead of reaching the database. The max bound keeps L1 from growing without limit.

Without invalidation, a value updated on one instance stays stale in the other instances’ L1 until its TTL runs out. Here invalidate deletes the Redis copy and publishes the key, and every instance drops its L1 entry when the message arrives. Redis pub/sub delivers at most once: a subscriber that is disconnected at that moment never sees the message, so the one-minute L1 TTL stays as the upper bound on staleness. Redis client-side caching (CLIENT TRACKING) moves the same bookkeeping into the server and the client library, which evicts a tracked key when any client writes it; node-redis and redis-py support it from v5.1.0.

The Performance Case#

The advantage is structural, and you can read it off the two access paths:

-- Relational: session lookup spanning three tables
SELECT u.name, u.email, p.theme, p.language, s.cart_items
FROM users u
JOIN user_preferences p ON u.id = p.user_id
JOIN user_sessions s ON u.id = s.user_id
WHERE s.session_id = 'abc123';

-- Key-value: one round trip, one hash probe
GET session:abc123

That comparison flatters the key-value side, because most of the cost sits in the joins. Store the session as one denormalized row and the relational read becomes a single primary-key lookup:

-- Fair comparison: one denormalized row, fetched by primary key
SELECT payload, expires_at FROM sessions WHERE session_id = $1;

That query walks one index and touches one row. Much of the gap closes, and a team that already runs PostgreSQL can serve sessions this way. The case for Redis rests on what comes on top of a fast lookup:

  • Expiry belongs to the key. SET session:abc123 ... EX 3600 removes the session on time; a table needs a scheduled job that deletes expired rows.
  • Data structures run on the server. Counters, hashes, sets and sorted sets update atomically in one round trip, with no read-modify-write in application code.
  • The working set lives in memory. Reads do not depend on whether the right pages are in the buffer cache.

Performance Characteristics That Matter#

A quota is a ceiling you can raise. Benchmark latency with your own payloads (redis-benchmark for Redis):

TechnologyDocumented latencyLimit to plan aroundDurabilityBest Use Case
Redis / ValkeyMicrosecond reads and writes (ElastiCache)Node memory; maxmemory-policy decides what happens when it fillsOptional: RDB snapshots can lose minutes, AOF everysec about one second; replication is asynchronousCaching, sessions
MemoryDBMicrosecond reads, single-digit millisecond writesNode memoryMulti-AZ transaction logDurable primary store on the Redis/Valkey API
DynamoDBSingle-digit millisecondsDefault quota: 40,000 RCU and 40,000 WCU per table (adjustable); 3,000 reads and 1,000 writes per second per partitionReplicated across three Availability ZonesServerless apps
etcdMeasure with your payloads2 GiB default storage quota, 8 GiB suggested maximum, 1.5 MiB per requestRaft consensus across membersConfig management
HazelcastNo network hop when embeddedJVM heapOne synchronous backup on another member by defaultJava ecosystems
MemcachedMeasure with your payloadsMemory, slab-based evictionNone: memory onlyPure caching
IMemoryCacheIn-process, no network hopProcess memoryLost on process restartSingle server

Core Advantages Over Relational Databases#

1. Less Work per Lookup A key-value GET is a hash lookup with no parse or plan step. A relational primary-key lookup is a B-tree descent, and it stays fast as long as no join follows it. In practice, per-query overhead and joins drive the gap.

2. Horizontal Scaling Key-value stores are designed for distributed hash tables, while relational databases typically scale vertically.

3. Schema Flexibility Adding a field needs no ALTER TABLE. The migration moves into the code that reads old values:

// Evolution over time without migrations
// Version 1
const userSession_v1 = {
  userId: "1001",
  expiresAt: 1642248600
};

// Version 2 (6 months later)
const userSession_v2 = {
  userId: "1001",
  expiresAt: 1642248600,
  preferences: { theme: "dark", language: "en" },
  deviceInfo: { browser: "Chrome", os: "macOS" }
};

// Version 3 (1 year later)
const userSession_v3 = {
  userId: "1001",
  expiresAt: 1642248600,
  preferences: { theme: "dark", language: "en" },
  deviceInfo: { browser: "Chrome", os: "macOS" },
  features: ["beta_feature_1", "experimental_ui"],
  analytics: { lastPageView: "/dashboard", sessionStart: 1642245000 }
};
// No ALTER TABLE, but readers must still handle v1 and v2 sessions
// (no preferences, no features) until those keys expire

Sessions written before a release stay in the store until their TTL runs out, so every field added since needs a default in the code that reads it.

When to Choose Each Approach#

Choose Key-Value When:

  • Simple access patterns (lookup by key)
  • High performance requirements (<10ms)
  • Flexible schema requirements
  • Horizontal scaling needed
  • Caching or session management

Choose Relational When:

  • Complex queries with JOINs
  • ACID transactions across multiple entities
  • Reporting and analytics workloads
  • Data integrity constraints critical

Redis, Valkey, and the License Change#

Redis 7.2 and earlier ship under the BSD-3-Clause license. Redis 7.4 moved to a dual RSALv2/SSPLv1 license, and Redis 8 added AGPLv3 as a third option. Redis Ltd. itself describes RSALv2 and SSPLv1 as source-available licenses that are not open source; AGPLv3 is OSI-approved.

For an application that uses Redis as its own cache or session store, the change rarely matters. It matters when Redis is part of what you offer to others. RSALv2 forbids providing the software to third parties as a managed service. SSPLv1 requires publishing the source of your management layers when you offer the product as a service. AGPLv3 targets code that runs over a network and requires making the source and your modifications available. If customers reach Redis through your product, have the license reviewed or run Valkey.

Valkey continues development from Redis 7.2.4 under the BSD-3-Clause license, backed by the Linux Foundation. AWS describes it as a drop-in replacement for Redis OSS 7, and ElastiCache upgrades a Redis OSS cluster to Valkey in place, keeping the endpoint DNS name. On ElastiCache, Valkey is priced 20% below Redis OSS on node-based clusters and 33% below on Serverless. Every Redis recommendation in the sections that follow applies to Valkey as well.

Solutions by Tech Stack#

Ecosystem-specific guidance for implementing KV storage across common technology stacks:

Java Ecosystem#

// Java: Hazelcast embedded in a Spring Boot service
@Configuration
public class HazelcastConfig {
    @Bean
    public Config hazelcastConfig() {
        Config config = new Config();
        JoinConfig join = config.getNetworkConfig().getJoin();
        join.getMulticastConfig().setEnabled(false);
        join.getKubernetesConfig().setEnabled(true)
            .setProperty("namespace", "shop")
            .setProperty("service-name", "session-service");
        return config;
    }
}

@Service
public class UserSessionService {
    private final IMap<String, UserSession> sessions;

    // Spring Boot builds the HazelcastInstance from the Config bean above
    public UserSessionService(HazelcastInstance hz) {
        this.sessions = hz.getMap("user-sessions");
    }

    public UserSession getSession(String sessionId) {
        return sessions.get(sessionId);  // Distributed, in-memory
    }
}

Two details matter in production. Spring Boot owns the instance: when a Config bean exists and no client configuration is found, it starts an embedded member from that bean. The join section names the discovery mechanism explicitly. Left alone, Hazelcast tries to auto-detect its environment and falls back to multicast, which most production networks block; Kubernetes or TCP/IP discovery is the predictable choice.

SolutionIntegrationBest ForIntegration Complexity
HazelcastNative JVM embeddingDistributed caching, computationLow (native)
RedisJedis, Lettuce clientsExternal caching, sessionsMedium
Chronicle MapOff-heap storageLow-latency, large datasetsHigh
InfinispanRed Hat ecosystemJBoss/WildFly integrationMedium
EhcacheHibernate integrationJPA second-level cacheLow

.NET Ecosystem#

// .NET: Multi-tier caching approach
public class CacheService
{
    private readonly IMemoryCache _memoryCache;
    private readonly IDistributedCache _distributedCache;

    public async Task<T> GetAsync<T>(string key)
    {
        // L1: In-memory cache
        if (_memoryCache.TryGetValue(key, out T value))
            return value;

        // L2: Distributed cache (Redis)
        var serialized = await _distributedCache.GetStringAsync(key);
        if (serialized != null)
        {
            value = JsonSerializer.Deserialize<T>(serialized);
            _memoryCache.Set(key, value, TimeSpan.FromMinutes(5));
            return value;
        }

        return default(T);
    }
}
SolutionIntegrationBest ForSetup Time
IMemoryCacheBuilt-in ASP.NET CoreSingle-server caching1 hour
IDistributedCacheRedis, SQL ServerMulti-server caching1 day
RedisStackExchange.RedisHigh-performance distributed1 day
Azure Cache for RedisManaged RedisAzure-native applications4 hours
SQL Server CacheBuilt-in providerExisting SQL infrastructure4 hours

Node.js/JavaScript Ecosystem#

// Node.js: Redis with a bounded in-process fallback
import Redis from 'ioredis';
import { LRUCache } from 'lru-cache';

class CacheService {
    constructor() {
        this.redis = new Redis({
            host: 'localhost',
            port: 6379,
            maxRetriesPerRequest: 3
        });
        // Bounded size and a 1 min TTL: no unbounded Map, no timer per key
        this.memoryCache = new LRUCache({ max: 5_000, ttl: 60_000 });
    }

    async get(key) {
        // L1: In-memory
        const local = this.memoryCache.get(key);
        if (local !== undefined) {
            return local;
        }

        // L2: Redis
        try {
            const value = await this.redis.get(key);
            if (value !== null) {
                const parsed = JSON.parse(value);
                if (parsed !== null) this.memoryCache.set(key, parsed); // lru-cache does not store null
                return parsed;
            }
        } catch (error) {
            console.error('Redis error:', error); // degrade to a cache miss
        }

        return null;
    }
}

Programming Language Decision Matrix#

Yes

No

Java

.NET

Node.js

Python

Go

Spring/Hibernate

General

Red Hat/JBoss

Configuration

Caching

Local Storage

Need Key-Value Storage?

Single Server?

In-Memory Cache

Programming Language?

.NET: IMemoryCache

Node.js: lru-cache

Python: cachetools

Go: bounded LRU cache

Ecosystem?

Redis + IDistributedCache

Redis + ioredis

Redis + redis-py

Use Case?

Hazelcast/Ehcache

Redis

Infinispan

etcd

Redis

BadgerDB

Decision Matrices in Practice#

These matrices help guide technology selection decisions:

Use Case-Based Selection Matrix#

Use CasePrimary ChoiceAlternativeAvoidReason
Session Storage (Web Apps)Redis or Valkey (IDistributedCache in .NET)DynamoDB (serverless)etcd; in-process caches behind a load balancerSessions need fast read/write, TTL support, and one copy every instance can see
Database Query CachingRedis, MemcachedIn-memory (.NET/Java)DynamoDBNeed fast eviction policies, cost control
Configuration Managementetcd, ConsulRedisDynamoDBNeed consistency, watching, hierarchical keys
Real-time AnalyticsRedis (sorted sets)HazelcastMemcachedNeed atomic operations, data structures
Service Discoveryetcd, ConsulRedis pub/subFile-basedNeed registration, health checks, watches

Deployment Shape Decision Matrix#

Three measurable inputs pick the store: how many processes need the same data, how large the working set is, and how many operations per second land on the hottest key.

Processes sharing the dataWorking setLoad on the hottest keyChoice
One processFits comfortably in the heapAnyIn-process cache (IMemoryCache, lru-cache, cachetools)
Two or more, behind a load balancerFits in one node’s memoryWithin one node’s capacityRedis or Valkey, primary plus replica
Two or moreLarger than one node’s memory, or more writes than one primary handlesSpread across many keysRedis or Valkey in cluster mode (sharded)
Two or more, serverless or scale-to-zeroAny sizeUnder 3,000 reads and 1,000 writes per second per keyDynamoDB
Cluster coordinationUnder etcd’s 2 GiB default quotaLow, watch-drivenetcd

Durability and Eviction#

Two more questions separate the rows above. They also settle whether sessions belong in Redis or in a durable database.

QuestionAnswerChoice
Can the store lose recent writes?Yes: a cache, or sessions where a forced re-login is acceptableRedis or Valkey. RDB snapshots can lose minutes of writes; AOF with appendfsync everysec limits the loss to about one second
No: the store is the system of record (carts, checkout state)MemoryDB (Multi-AZ transaction log) or DynamoDB. Redis replication is asynchronous, and even with WAIT, acknowledged writes can be lost during a failover
What happens when memory fills?Pure cachemaxmemory-policy allkeys-lru, the Redis docs’ default suggestion when nothing argues otherwise
Sessions and cache share one instanceSplit them into two instances, as the Redis docs advise. Under allkeys-lru, a burst of cache writes can evict live sessions and log users out
Keys must never be dropped silentlynoeviction: writes fail with an error once memory is full, while reads keep working

Technology Selection Decision Logic#

Yes

.NET

Other

No

Configuration

Other

Serverless

Other

Java + Embedded

Other

Yes

No

Low budget + No ops team

Other

Start: KV Storage Selection

Single Server?

Language?

IMemoryCache

In-memory cache

Use Case?

etcd

Workload Type?

DynamoDB

Ecosystem?

Hazelcast

Must survive node loss?

MemoryDB or DynamoDB

Budget & Ops?

Managed Redis or Valkey

Redis or Valkey - Default Choice

Ecosystem-Native Alternatives Get Skipped#

Redis is the reflex answer for distributed caching, including on stacks that already ship a cluster-aware cache. A Spring Boot service that adds Redis takes on a separate process to run, a network hop per lookup, and one more component in the on-call rotation. Hazelcast embedded in the same JVM removes all three for cache data that does not need to outlive the cluster.

The trade-off runs the other way as soon as a second runtime needs the same data, or once the working set outgrows what you want to hold in the application heap. At that point the network hop buys you independence and a memory budget you can size separately.

Cost Considerations and Trade-offs#

At a working set around 100GB, the shape of the bill matters more than the sticker price. The ranking below is stable across providers; the absolute numbers move with region, instance family, and traffic profile, so price the two or three shortlisted options in the vendor calculator before committing.

SolutionCost shapePerformanceOperational OverheadBest For
IMemoryCacheNo extra spend, in-processFastestNoneSingle server
Redis or Valkey (Self-managed)Instance cost onlyFastHighCost-sensitive
Redis OSS (Managed)Instance cost plus service premiumFastLowCloud-native apps
Valkey (Managed, ElastiCache)Same shape, priced 20% below Redis OSS on nodes and 33% below on ServerlessFastLowNew managed deployments
MemoryDBNode hours plus a charge per GB writtenFast reads, slower writesLowData that must survive a failover
DynamoDBPer-request or provisioned capacityGoodNoneVariable workloads
Cosmos DBProvisioned RU/s plus storageGoodNoneEnterprise
etcdNo extra spend on an existing K8s control planeModerateMediumConfiguration only

Failure Modes to Plan For#

IMemoryCache Does Not Survive a Load Balancer#

IMemoryCache lives inside one process. It behaves perfectly in development and on a single server, then breaks the moment a load balancer routes the next request to a different instance: the session is not there, and the user is logged out. The failure is intermittent and traffic-dependent, which is what makes it expensive to diagnose.

Session state that has to outlive a single process belongs in IDistributedCache backed by Redis or an equivalent. Keep IMemoryCache for data that is cheap to rebuild per instance, such as parsed configuration or lookup tables.

Redis-Specific Pitfalls#

# Problem: Blocking operations in Redis
SLOWLOG GET 10  # Check for slow operations
# Common blockers: KEYS *, FLUSHALL, large SORT operations

# Solution: Use non-blocking alternatives
SCAN 0 MATCH "user:*" COUNT 100  # Instead of KEYS user:*

DynamoDB Hot Partition Problem#

A per-user partition key already spreads load across partitions, because every user is a different key value. Throttling starts when one partition receives more than 3,000 reads or 1,000 writes per second. Adaptive capacity, on for every table at no extra cost, can move a frequently accessed item onto its own partition, and that single item can then use the full per-partition maximum. It does not split item collections when the table has a local secondary index. Write sharding is for the key that still exceeds it, usually a global counter or a daily aggregate, and it moves the cost to reads:

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, UpdateCommand } from "@aws-sdk/lib-dynamodb";

const db = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const TABLE = "app-data";

// Not a hot key: `USER#${userId}` spreads load, because every user
// is a different partition key value.

// A hot key is ONE partition key value that needs more than
// 3,000 reads or 1,000 writes per second, such as a global vote counter.
const SHARDS = 10;

export async function recordVote(pollId: string): Promise<void> {
  const shard = Math.floor(Math.random() * SHARDS);
  await db.send(new UpdateCommand({
    TableName: TABLE,
    Key: { pk: `POLL#${pollId}#${shard}` },
    UpdateExpression: "ADD votes :one",
    ExpressionAttributeValues: { ":one": 1 },
  }));
}

// The cost moves to reads: one GetItem per shard, then a merge in code
export async function countVotes(pollId: string): Promise<number> {
  const shards = await Promise.all(
    Array.from({ length: SHARDS }, (_, shard) =>
      db.send(new GetCommand({ TableName: TABLE, Key: { pk: `POLL#${pollId}#${shard}` } })),
    ),
  );
  return shards.reduce((sum, res) => sum + Number(res.Item?.votes ?? 0), 0);
}

Each vote is one write to a random shard; each count is ten reads and a sum. A random suffix also hides which shard holds a given item. When you need to read or update one item directly, derive the suffix from an attribute you already know, such as a hash of the order ID, as the DynamoDB write-sharding guide shows.

Decisions That Are Expensive to Retrofit#

These choices are cheap to make early and expensive to fix later:

  1. Start with observability: hit rate, eviction rate, latency, and cost should be visible before the cache carries production traffic
  2. Decide the region story early: a single-region store is a fine answer, but retrofitting replication onto a key schema that assumed one region is not
  3. Keep provisioning in code: cache clusters get resized, failed over, and rebuilt, and each of those is a manual event when the instance was created by hand

Where the Default Holds#

Override the default in four situations. A single server with no failover story is better served by an in-process cache. Serverless workloads with swinging traffic fit DynamoDB’s managed scaling and per-request billing. Configuration and coordination belong in etcd, which is built for consistency and watches rather than raw throughput. A deployment that runs entirely on the JVM can embed Hazelcast and skip the network hop. Durability is a separate question from the store family: when acknowledged writes must survive a failover, run the Redis API on MemoryDB or move that data to DynamoDB.

Whichever you pick, plan for it to be unavailable: retries, a circuit breaker, and a defined behavior for requests that arrive while the cache is down.

References#

Related posts