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.
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 3600removes 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):
| Technology | Documented latency | Limit to plan around | Durability | Best Use Case |
|---|---|---|---|---|
| Redis / Valkey | Microsecond reads and writes (ElastiCache) | Node memory; maxmemory-policy decides what happens when it fills | Optional: RDB snapshots can lose minutes, AOF everysec about one second; replication is asynchronous | Caching, sessions |
| MemoryDB | Microsecond reads, single-digit millisecond writes | Node memory | Multi-AZ transaction log | Durable primary store on the Redis/Valkey API |
| DynamoDB | Single-digit milliseconds | Default quota: 40,000 RCU and 40,000 WCU per table (adjustable); 3,000 reads and 1,000 writes per second per partition | Replicated across three Availability Zones | Serverless apps |
| etcd | Measure with your payloads | 2 GiB default storage quota, 8 GiB suggested maximum, 1.5 MiB per request | Raft consensus across members | Config management |
| Hazelcast | No network hop when embedded | JVM heap | One synchronous backup on another member by default | Java ecosystems |
| Memcached | Measure with your payloads | Memory, slab-based eviction | None: memory only | Pure caching |
| IMemoryCache | In-process, no network hop | Process memory | Lost on process restart | Single 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.
| Solution | Integration | Best For | Integration Complexity |
|---|---|---|---|
| Hazelcast | Native JVM embedding | Distributed caching, computation | Low (native) |
| Redis | Jedis, Lettuce clients | External caching, sessions | Medium |
| Chronicle Map | Off-heap storage | Low-latency, large datasets | High |
| Infinispan | Red Hat ecosystem | JBoss/WildFly integration | Medium |
| Ehcache | Hibernate integration | JPA second-level cache | Low |
.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);
}
}
| Solution | Integration | Best For | Setup Time |
|---|---|---|---|
| IMemoryCache | Built-in ASP.NET Core | Single-server caching | 1 hour |
| IDistributedCache | Redis, SQL Server | Multi-server caching | 1 day |
| Redis | StackExchange.Redis | High-performance distributed | 1 day |
| Azure Cache for Redis | Managed Redis | Azure-native applications | 4 hours |
| SQL Server Cache | Built-in provider | Existing SQL infrastructure | 4 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#
Decision Matrices in Practice#
These matrices help guide technology selection decisions:
Use Case-Based Selection Matrix#
| Use Case | Primary Choice | Alternative | Avoid | Reason |
|---|---|---|---|---|
| Session Storage (Web Apps) | Redis or Valkey (IDistributedCache in .NET) | DynamoDB (serverless) | etcd; in-process caches behind a load balancer | Sessions need fast read/write, TTL support, and one copy every instance can see |
| Database Query Caching | Redis, Memcached | In-memory (.NET/Java) | DynamoDB | Need fast eviction policies, cost control |
| Configuration Management | etcd, Consul | Redis | DynamoDB | Need consistency, watching, hierarchical keys |
| Real-time Analytics | Redis (sorted sets) | Hazelcast | Memcached | Need atomic operations, data structures |
| Service Discovery | etcd, Consul | Redis pub/sub | File-based | Need 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 data | Working set | Load on the hottest key | Choice |
|---|---|---|---|
| One process | Fits comfortably in the heap | Any | In-process cache (IMemoryCache, lru-cache, cachetools) |
| Two or more, behind a load balancer | Fits in one node’s memory | Within one node’s capacity | Redis or Valkey, primary plus replica |
| Two or more | Larger than one node’s memory, or more writes than one primary handles | Spread across many keys | Redis or Valkey in cluster mode (sharded) |
| Two or more, serverless or scale-to-zero | Any size | Under 3,000 reads and 1,000 writes per second per key | DynamoDB |
| Cluster coordination | Under etcd’s 2 GiB default quota | Low, watch-driven | etcd |
Durability and Eviction#
Two more questions separate the rows above. They also settle whether sessions belong in Redis or in a durable database.
| Question | Answer | Choice |
|---|---|---|
| Can the store lose recent writes? | Yes: a cache, or sessions where a forced re-login is acceptable | Redis 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 cache | maxmemory-policy allkeys-lru, the Redis docs’ default suggestion when nothing argues otherwise |
| Sessions and cache share one instance | Split 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 silently | noeviction: writes fail with an error once memory is full, while reads keep working |
Technology Selection Decision Logic#
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.
| Solution | Cost shape | Performance | Operational Overhead | Best For |
|---|---|---|---|---|
| IMemoryCache | No extra spend, in-process | Fastest | None | Single server |
| Redis or Valkey (Self-managed) | Instance cost only | Fast | High | Cost-sensitive |
| Redis OSS (Managed) | Instance cost plus service premium | Fast | Low | Cloud-native apps |
| Valkey (Managed, ElastiCache) | Same shape, priced 20% below Redis OSS on nodes and 33% below on Serverless | Fast | Low | New managed deployments |
| MemoryDB | Node hours plus a charge per GB written | Fast reads, slower writes | Low | Data that must survive a failover |
| DynamoDB | Per-request or provisioned capacity | Good | None | Variable workloads |
| Cosmos DB | Provisioned RU/s plus storage | Good | None | Enterprise |
| etcd | No extra spend on an existing K8s control plane | Moderate | Medium | Configuration 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:
- Start with observability: hit rate, eviction rate, latency, and cost should be visible before the cache carries production traffic
- 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
- 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#
- Redis Licenses (opens in new tab) - Which license covers which Redis version (BSD up to 7.2, RSALv2/SSPLv1 for 7.4, a third AGPLv3 option from Redis 8) and the limits each one sets.
- Linux Foundation Launches Open Source Valkey Community (opens in new tab) - Announcement of Valkey, continuing development from Redis 7.2.4 under the BSD 3-clause license.
- Upgrading Engine Versions, Including Redis OSS to Valkey (ElastiCache) (opens in new tab) - Describes Valkey as a drop-in replacement for Redis OSS 7 and the in-place cross-engine upgrade.
- Amazon ElastiCache Pricing (opens in new tab) - Node-based and Serverless prices per engine, including the lower Valkey rates.
- What Is MemoryDB (opens in new tab) - Durable in-memory database on the Valkey and Redis OSS APIs, with a Multi-AZ transaction log and its documented read and write latency.
- Amazon MemoryDB Pricing (opens in new tab) - Pricing dimensions: node hours, data written per GB, snapshot storage, and data transfer.
- Redis Data Types (opens in new tab) - Comprehensive guide to Redis data structures: strings, lists, sets, sorted sets, hashes, streams, and more.
- Redis Persistence (RDB and AOF) (opens in new tab) - Persistence options and how much data each one can lose: minutes with RDB snapshots, about one second with AOF
everysec. - Redis Replication (opens in new tab) - Leader-follower replication, why it is asynchronous by default, and why
WAITdoes not prevent losing acknowledged writes during a failover. - Redis Key Eviction (opens in new tab) - The
maxmemorydirective, everymaxmemory-policyvalue, and the advice to split cache and persistent keys into separate instances. - Redis Client-Side Caching (opens in new tab) - Server-assisted tracking and invalidation of client caches, with the client library versions that support it.
- Redis Pub/Sub (opens in new tab) - Channel messaging and its at-most-once delivery semantics.
- lru-cache (opens in new tab) - Size-bounded LRU cache for Node.js with per-entry TTL; documents the
maxandttloptions. - Amazon DynamoDB Developer Guide (opens in new tab) - Data model, single-digit millisecond performance, and replication across three Availability Zones.
- DynamoDB Service Quotas (opens in new tab) - Default per-table and per-account throughput quotas, and the note that they are adjustable defaults rather than maximums.
- DynamoDB Burst and Adaptive Capacity (opens in new tab) - The 3,000 read and 1,000 write per-partition limits and how adaptive capacity isolates frequently accessed items.
- Using Write Sharding in DynamoDB (opens in new tab) - Random and calculated partition key suffixes, and the multi-query read they require.
- etcd (opens in new tab) - Project overview: a strongly consistent, distributed key-value store replicated with the Raft protocol.
- etcd System Limits (opens in new tab) - Request size limit, the 2 GiB default storage quota, and the 8 GiB suggested maximum.
- Hazelcast Map Backups (opens in new tab) - Synchronous and asynchronous backup counts for distributed maps; the default is one synchronous backup.
- Hazelcast Discovery Mechanisms (opens in new tab) - Auto-detection, the multicast fallback, and the Kubernetes and TCP/IP alternatives for production.
- Hazelcast with Spring Boot (opens in new tab) - How Spring Boot creates a client or an embedded
HazelcastInstancefrom aConfigbean or configuration file. - Distributed Caching in ASP.NET Core (opens in new tab) - Microsoft’s guidance on IDistributedCache, its Redis and SQL Server providers, and when in-process caching stops working.
- Memcached Wiki (opens in new tab) - Project documentation covering the protocol, memory allocation via slabs, and eviction behavior.
Related posts
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
Choose the right database across SQL, NoSQL, NewSQL, and edge options: the trade-offs of each category, selection criteria, and a decision framework.
data-storage-orm · postgresql · redis +6
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
Strategies to prevent and handle DynamoDB throttling in Single Table Design: partition key design, write sharding, capacity modes, DAX, and retry patterns.
dynamodb · aws · reliability +4
Model relationships, choose between GSI and LSI, integrate DAX caching, and avoid hot partitions in production DynamoDB single-table designs with working examples.
dynamodb · data-storage-orm · aws +1