Key-Value Stores: Redis and DynamoDB Patterns

Compare Redis and DynamoDB for caching, sessions, and key-value workloads, with version-scoped guidance on durability, consistency, limits, and locks.

published: reading time: 36 min read author: Geek Workbench updated: November 21, 2026
Quick Summary

This guide compares Redis Open Source 8.10.3 with Amazon DynamoDB, a managed service whose engine version AWS controls. It explains how Redis persistence and eviction depend on configuration, where DynamoDB offers eventual or strong reads, and which limits apply to items and transactions. It also uses a workload worksheet instead of physical-partition guesses and explains when Redis lock leases need owner checks and fencing.

Key-value stores: Redis and DynamoDB patterns

The key-value model starts with a lookup key and its associated value. Some systems add indexes, transactions, or richer value types, but reads still depend on choosing access patterns the store can serve efficiently.

The Redis server examples target Redis Open Source 8.10.3, the current stable release listed on 2026-11-21 (release listing). The Python snippets use redis-py 8.1.0 (release listing) and Boto3 1.44.5 (release listing); pin client versions in an application lockfile or validate upgrades before using them. Managed Redis-compatible services may expose different versions, defaults, and failover behavior, so check the provider’s documentation. DynamoDB is an AWS-managed service; customers do not select its storage-engine version. AWS service behavior and quotas can change, so check the linked documentation before sizing or deploying a design.

Redis keeps its working data in memory and can write snapshots or an append-only file (AOF) to disk. DynamoDB is managed by AWS, which states that a successful write acknowledged with HTTP 200 has been durably persisted. Table and local secondary index reads can be eventual or strong; global secondary index and stream reads are eventual. Neither description supplies a general latency target, so measure the behavior of the selected configuration, Region, and workload. See DynamoDB read consistency.


The key-value model

At its core, the model is:

# Basic operations
store.set(key, value)
value = store.get(key)
store.delete(key)
exists = store.exists(key)

The store serves reads supported by the chosen key or index. DynamoDB can filter query results, but filtering does not turn a table into an arbitrary-query engine.

Key lookups can be simple, but their cost still depends on network round trips, item size, indexes, consistency mode, and workload. Redis Cluster and DynamoDB also distribute data differently: Redis exposes hash slots and node routing, while DynamoDB manages physical partitions behind the service API.

flowchart LR
    Client["Client"]
    Redis["Redis Cluster<br/>(3 Nodes)"]
    A["Node A<br/>hash_tag: {user}"]
    B["Node B<br/>hash_tag: {order}"]
    C["Node C<br/>hash_tag: {product}"]
    Client --> Redis
    Redis --> A & B & C

Redis Cluster maps keys to 16,384 hash slots. A hash tag in braces makes keys such as {user}:123 and {user}:456 land in the same slot, which is useful for multi-key operations. See the Redis Cluster specification for slot and hash-tag behavior. DynamoDB hashes partition-key values internally, but AWS manages the physical partitions and their placement; applications should design for well-distributed access rather than assume a key maps to a known node.


Redis: in-memory speed

Redis Open Source 8.10.3 stores its working dataset in memory. RDB snapshots and AOF can persist data, but they have different recovery points and write costs. Replication is asynchronous, so persistence and replicas do not make every Redis deployment equivalent to a durable database. See the Redis persistence guide and verify the behavior of the deployment you run.

Basic operations

import redis

r = redis.Redis(host='localhost', port=6379, db=0)

# String operations
r.set('user:123:session', json.dumps(session_data))
r.set('rate:limit:192.168.1.1', 100, ex=60)  # With 60-second TTL
value = r.get('user:123:session')

# Multiple operations (pipelines reduce round trips, but are not transactions)
pipe = r.pipeline()
pipe.hset('user:123', mapping={'name': 'Alice', 'email': 'alice@example.com'})
pipe.expire('user:123', 3600)
pipe.execute()

# Atomic counters
r.incr('api:request:count')
r.incrby('user:123:balance', 100)

The EX parameter expresses expiration in seconds, while PX expresses it in milliseconds. Choose the unit that fits the application’s time window, but do not treat TTL as an exact-time scheduler: expiry processing and command timing can affect when a key becomes unavailable.

Pipeline batching sends multiple commands before waiting for their replies, which can reduce network round trips. It does not make the commands atomic: a connection failure can leave some commands applied and others without a reply. Use a Redis transaction or Lua script when the operation needs atomicity, and still handle an ambiguous reply after a connection failure.

Redis-py reports server-side command errors such as type mismatches as ResponseError, and connection or timeout failures with separate exception types. Retry only operations that are safe to repeat; a timeout can leave a write’s outcome unknown. Use bounded backoff for transient failures, and fix type errors in the application rather than retrying them. Set socket_connect_timeout and socket_timeout so a saturated Redis does not block the application indefinitely.

Data structures beyond strings

Redis stores several data structures, each with commands suited to different access patterns.

# Lists (queues, activity feeds)
r.lpush('queue:jobs', 'job1', 'job2', 'job3')
next_job = r.rpop('queue:jobs')

# Sets (unique items, tags)
r.sadd('user:123:likes', 'item1', 'item2', 'item3')
is_member = r.sismember('user:123:likes', 'item1')
all_items = r.smembers('user:123:likes')

# Sorted sets (leaderboards, priorities)
r.zadd('leaderboard', {'alice': 100, 'bob': 200, 'charlie': 150})
top_players = r.zrevrange('leaderboard', 0, 9, withscores=True)
rank = r.zrevrank('leaderboard', 'alice')

# Hashes (objects)
r.hset('product:SKU-001', mapping={
    'name': 'Gaming Laptop',
    'price': 1299.99,
    'stock': 50
})
product = r.hgetall('product:SKU-001')

Each data structure fits different access patterns. Lists can implement a queue with LPUSH and RPOP, or hold an activity feed for LRANGE reads. Sets store unique members; SISMEMBER has expected O(1) lookup cost. Sorted sets order members by score and support rank operations such as ZREVRANK; check the Redis command reference for operation costs and version details.

Hashes let you update fields independently, such as incrementing a view count without rewriting a serialized object. A whole-object JSON string may be simpler when every read needs every field. Memory use depends on object shape and Redis encoding, so measure representative values with MEMORY USAGE instead of assuming one representation is always smaller. Field expiration behavior is version-specific; check the Redis 8.10.3 command reference before relying on it.

TTL and expiration

Time-to-live (TTL) gives a key an expiration time. Redis removes expired keys as part of its expiration process; the exact moment a key disappears is not a scheduling guarantee. A TTL is useful for sessions, counters, and cache entries, but it does not replace an explicit data-retention or invalidation policy.

Set a TTL when writing with EX for seconds or PX for milliseconds. A key without a TTL remains until it is deleted, evicted, or the dataset is otherwise changed. For temporary data, missing expiration can cause unexpected growth.

import json
import uuid

# Session with 30-minute expiry
r.setex('session:abc123', 1800, json.dumps(session_data))

# For rate limiting, see the atomic Lua example below.
# This lease example is not mutual exclusion; read the lock section first.
token = str(uuid.uuid4())
acquired = r.set('lock:resource-123', token, nx=True, px=10_000)

This Redis 8.10.3 example uses the SET command’s NX and PX options. It creates a time-limited lease; it does not by itself protect a downstream resource from a worker whose lease expired while it was paused.


DynamoDB: managed persistent storage

Amazon DynamoDB is an AWS-managed service. AWS manages its storage engine and physical partitions; you choose keys, indexes, capacity mode, consistency options, and Region configuration. DynamoDB has no customer-selected engine version. The examples use Boto3 1.44.5’s Resource API; pin that SDK version in your application’s dependency lockfile or validate upgrades, and check the linked AWS service docs for current behavior and quotas.

Table structure

DynamoDB has a simple primary key: either a partition key alone, or a partition key plus sort key.

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('UserSessions')

# Put and get items
table.put_item(Item={
    'userId': 'user-123',
    'sessionId': 'session-abc',
    'data': {'preferences': {'theme': 'dark'}},
    'expiresAt': int(time.time()) + 3600
})

response = table.get_item(
    Key={
        'userId': 'user-123',
        'sessionId': 'session-abc'
    }
)

The partition key is part of the item’s primary key and an input to DynamoDB’s internal distribution. AWS manages where data is stored; application code should not depend on a partition key mapping to one physical node. A table keyed by userId lets you query a user’s items together when paired with a sort key, but a skewed access pattern can still create throttling. Design keys around query needs and observed traffic distribution.

The sort key is optional and enables ordered and range queries for a partition-key value. With userId as the partition key and timestamp as the sort key, a Query can retrieve a user’s items for a time range. A table without a sort key still supports operations such as Query on its partition key; GetItem is for retrieving a known primary key. Put attributes in the key only when the access pattern needs them there.

The current DynamoDB item-size limit is 400 KB, including attribute names and values. This is a service constraint, not a target size; review the live DynamoDB constraints and Service Quotas before sizing a design. Short attribute names can reduce item size, but choose names that remain maintainable. Capacity mode, item size, indexes, consistency, and key distribution all affect throughput and cost.

Access patterns drive key design

In DynamoDB, you design keys around the queries the application needs. A Query uses a table or index key; a FilterExpression can discard returned items but does not let the service search an arbitrary attribute as a key.

# Single table design: multiple entity types in one table
# Key: PK (partition key), SK (sort key)

# User entity
{'PK': 'USER#alice', 'SK': 'PROFILE', 'name': 'Alice', 'email': 'alice@example.com'}

# Orders for user
{'PK': 'USER#alice', 'SK': 'ORDER#2024-01-01', 'total': 129.99, 'items': [...]}
{'PK': 'USER#alice', 'SK': 'ORDER#2024-01-15', 'total': 49.99, 'items': [...]}

# Products
{'PK': 'PRODUCT#LAPTOP-001', 'SK': 'METADATA', 'name': 'Gaming Laptop', 'price': 1299.99}

# Query all orders for a user
response = table.query(
    KeyConditionExpression=Key('PK').eq('USER#alice') & Key('SK').begins_with('ORDER#')
)

# Query single user profile
response = table.get_item(
    Key={'PK': 'USER#alice', 'SK': 'PROFILE'}
)

Single-table design can keep related access patterns together, but it requires deliberate key and index design. Global secondary indexes (GSIs) can be added after table creation, while local secondary indexes (LSIs) must be defined when the table is created. Adding an index can require backfill and additional capacity. If access patterns change, plan the index or data migration rather than assuming the table layout will adapt automatically.

The begins_with operator on sort keys enables prefix-based grouping. ORDER#2024-01 catches all January 2024 orders. ORDER#2024-01-15 targets a specific day. This pattern replaces date-range queries you would write as WHERE created_at BETWEEN x AND y in SQL. Because sort keys are ordered lexically, dates must be zero-padded (2024-01-01, not 2024-1-1) for prefix matching to work across month boundaries.

Do not choose single-table design by counting entity types. It works when the entities share access patterns and can use a coherent key scheme. Separate tables may be easier to operate when their throughput, retention, or access needs differ. Prototype the important queries and index projections before committing to either layout.

Global secondary indexes

When you need alternative access patterns, use GSIs.

# Create table with GSI for email lookup
table = dynamodb.create_table(
    TableName='Users',
    KeySchema=[
        {'AttributeName': 'userId', 'KeyType': 'HASH'}
    ],
    AttributeDefinitions=[
        {'AttributeName': 'userId', 'AttributeType': 'S'},
        {'AttributeName': 'email', 'AttributeType': 'S'}
    ],
    GlobalSecondaryIndexes=[
        {
            'IndexName': 'EmailIndex',
            'KeySchema': [{'AttributeName': 'email', 'KeyType': 'HASH'}],
            'Projection': {'ProjectionType': 'ALL'}
        }
    ],
    BillingMode='PAY_PER_REQUEST'
)

# Later, query by email
response = table.query(
    IndexName='EmailIndex',
    KeyConditionExpression=Key('email').eq('alice@example.com')
)

Reads from GSIs are always eventually consistent; strong consistency is available for table and LSI reads, but not GSI or stream reads. Do not assume a GSI reflects a completed write immediately. If a read must observe a just-completed write, use a strongly consistent base-table or LSI read when that access pattern fits. See DynamoDB read consistency.

Indexes add storage and write costs. A GSI with ProjectionType: ALL copies all attributes; an INCLUDE or KEYS_ONLY projection may be a better fit when the query needs fewer fields. Check the current index quotas and capacity behavior in AWS documentation. For details on ProjectionType, see the DynamoDB secondary-index guide.

The current AWS quota guide lists a default of 20 GSIs per table and allows up to 5 LSIs per table. Quotas can change, and some are adjustable; check the current DynamoDB quotas for the relevant Region. LSIs share the base table’s partition key and must be created with the table. GSIs can be added later, subject to service constraints and any backfill work.

Use cases: key-value stores in practice

Caching

Store frequently accessed data in Redis to reduce load on the source database.

def get_user_profile(user_id):
    cache_key = f'user:profile:{user_id}'

    # Try cache first
    cached = redis.get(cache_key)
    if cached:
        return json.loads(cached)

    # Cache miss - fetch from database
    profile = database.fetch_user(user_id)

    # Store in cache for next time
    redis.setex(cache_key, 300, json.dumps(profile))  # 5 minute TTL

    return profile

This is cache-aside: read from Redis first, then load and cache a miss. A 300-second TTL bounds how long an untouched cache entry can remain, but it does not guarantee freshness during that period. For prices or inventory, invalidate or update the cache when the source changes if the application cannot tolerate stale reads. Review AWS’s database caching patterns and Redis’s key-expiration commands.

Track keyspace_hits / (keyspace_hits + keyspace_misses) alongside origin load, memory use, and request latency. There is no universal hit-ratio threshold: a low hit ratio may still help expensive queries, while a high ratio can hide stale data or a cache that costs more to operate than it saves.

Cache warming can reduce misses after startup or a deployment, but loading too much data wastes memory and adds pressure to the source database. Use application or database access metrics to select a bounded set of likely requests, then monitor misses and origin load after rollout.

Session storage

Sessions are naturally key-value: session ID maps to session data.

# Web session
session_id = cookies.get('session_id')
if not session_id:
    session_id = generate_session_id()
    redis.setex(f'session:{session_id}', 86400, json.dumps({}))

session_data = json.loads(redis.get(f'session:{session_id}'))
session_data['page_views'] = session_data.get('page_views', 0) + 1
redis.setex(f'session:{session_id}', 86400, json.dumps(session_data))

Choose session lifetime from the application’s security and user-experience requirements. Redis expires keys according to their TTL; a cached session can still be lost through eviction or a Redis failure. See the Redis expiration commands. DynamoDB TTL is available too, but deletion is asynchronous, so check an expiry attribute during reads when an expired session must be rejected immediately. See the DynamoDB TTL documentation.

Session data stored as JSON in Redis is deserialized on every read. That may be fine for small sessions, but large payloads increase network transfer on every request. Store only the fields the request path needs in Redis and keep less frequently used data in the primary database when that fits the application.

If multiple requests update one session concurrently, a read-modify-write sequence can lose an update. Use an atomic Redis command or script for the specific update, a transaction with WATCH when optimistic retry fits, or separate keys for independently updated values. Redis’s transaction guide describes WATCH, MULTI, and EXEC.

Leaderboards

Redis sorted sets can keep members ordered by score and support rank queries.

def update_leaderboard(player_id, score):
    redis.zadd('leaderboard', {player_id: score})

def get_top_players(n=10):
    return redis.zrevrange('leaderboard', 0, n-1, withscores=True)

def get_player_rank(player_id):
    rank = redis.zrevrank('leaderboard', player_id)
    return rank + 1 if rank is not None else None

Redis sorted-set scores are floating-point numbers. Members with equal scores are ordered lexicographically, not by submission time. If ties need another rule, keep a separate timestamp or use application-level composite ordering rather than encoding timestamps as tiny score fractions, which can lose precision.

Leaderboard size grows unbounded with ZADD. In a game with millions of players, storing every player in one sorted set becomes memory-intensive. Partition the leaderboard by region, season, or skill tier. Query only the relevant partition. Archiving old seasons to a separate key or DynamoDB table keeps the active leaderboard lean.

Measure leaderboard size, update rate, and ranking-read rate on Redis 8.10.3. Redis Cluster shards by key, so one very large leaderboard key remains on one hash slot; sharding by season, region, or category only spreads load when those partitions match the queries. See the ZADD command reference for command semantics.

Rate limiting

Atomic operations enable distributed rate limiting.

def is_allowed(client_id, limit=100, window=60):
    key = f'ratelimit:{client_id}'

    # Lua script for atomic check-and-increment
    script = """
    local current = redis.call('GET', KEYS[1])
    if current and tonumber(current) >= tonumber(ARGV[1]) then
        return 0
    end
    current = redis.call('INCR', KEYS[1])
    if tonumber(current) == 1 then
        redis.call('EXPIRE', KEYS[1], ARGV[2])
    end
    return 1
    """

    result = redis.eval(script, 1, key, limit, window)
    return bool(result)

Redis executes the Lua script as one operation without interleaving other commands. This prevents two concurrent requests from both checking the counter at zero before either increments it. Without an atomic check and increment, both requests can pass even when the limit is exceeded.

Fixed window rate limiting (resetting the counter every minute) has a burst problem: a user can hit the limit at 0:59 and again at 1:01, getting double the allowed requests across the window boundary. Sliding window rate limiting uses sorted sets with timestamps as scores, removing expired entries before counting. This is more memory-intensive but eliminates the boundary burst.

Token bucket is an alternative that allows bursts while enforcing an average rate. It stores a last-request timestamp and available tokens; each request replenishes tokens based on elapsed time before deciding whether to pass. Implement it atomically and test boundary behavior. For limits that should apply before traffic reaches the application, a gateway-level limiter may fit better. See Redis’s Lua scripting guide for atomic server-side operations.

Distributed locks

A Redis key can provide a time-limited lease. If a stale owner could still write after its lease expires, the protected resource needs a way to reject that write. Prefer a database condition, transaction, or idempotent operation for critical state changes; use a Redis lease to reduce duplicate work where occasional overlap is acceptable.

import uuid

lock_key = 'lock:resource-123'
token = str(uuid.uuid4())
lease_ms = 10_000

# One primary: a short-lived lease, not durable mutual exclusion.
acquired = r.set(lock_key, token, nx=True, px=lease_ms)

# Release only if this caller still owns the lease.
release_if_owner = r.register_script("""
if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('DEL', KEYS[1])
end
return 0
""")
if acquired:
    release_if_owner(keys=[lock_key], args=[token])

The random token prevents one client from deleting another client’s lease if the first lease expired and a new owner acquired it. It does not stop the first client from continuing work after expiry. A paused process can wake after its TTL, overlap with the new owner, and write stale data. If a primary fails before its asynchronous replica receives the lock write, the promoted replica can let another client acquire what appears to be the same lock.

Use a fencing token when stale owners must be rejected. A fencing token is monotonic and is checked by the resource being protected; operations with a token older than the last accepted token are rejected. Generate it from an authoritative sequence or the protected system itself. A random UUID is an ownership token, not a fencing token. TTL renewal can reduce accidental expiry during long work, but it cannot prove the client stayed alive or prevent a paused process from resuming late.

Redis documents both the single-instance SET NX PX pattern and the multi-instance Redlock algorithm. Redlock has timing and clock assumptions, and Redis’s guide recommends fencing tokens for long-running work. Redis replication is asynchronous, so a primary/replica failover can lose the key that represented the lease. These patterns do not replace a database transaction or the protected resource’s concurrency control. For a database-owned lease, use conditional writes or a transaction and define how stale workers are rejected. See Redis distributed locks and DynamoDB transactions.

Use case Safer starting point
Cache refresh or duplicate background work Idempotent work plus a short SET lease; accept that duplicate work can still occur.
Updating a database row or account balance Use DynamoDB condition expressions or a transaction; do not rely on a Redis lease alone.
Scheduled job or leader election Use a lease with renewal, owner checks, and fencing enforced by the target; review the Redis lock guidance.
Cross-service coordination Choose a coordinator whose failure model fits the workflow. For AWS-managed data changes, use conditional writes or transactions; test pauses, partitions, and failover.

Redis eviction policies

On Redis Open Source 8.10.3, the maxmemory policy determines what happens when the configured memory limit is reached. Eviction is separate from persistence: a key can be evicted even when RDB or AOF is enabled. Select a policy based on whether every key is disposable and what the application does after a miss. Check the Redis eviction documentation for the current policy list and configuration details.

# Example settings; choose values from measured workload and host memory.
maxmemory 2gb
maxmemory-policy noeviction

# noeviction: reject writes, reads allowed (default)
# allkeys-lru: evict least recently used keys across all keys
# allkeys-random: evict random keys
# volatile-lru: evict LRU keys only in keys with TTL
# volatile-random: evict random keys with TTL
# volatile-ttl: evict keys with shortest TTL
# allkeys-lfu: evict least frequently used keys
# volatile-lfu: evict LFU keys with TTL

noeviction rejects writes that need more memory. allkeys-lru and allkeys-lfu may evict any key, including keys without TTLs. The corresponding volatile-* policies only consider keys with an expiry; if there are no eligible keys, writes can still fail. allkeys-lru is a common cache policy, not a safe default for mixed cache and durable application data. Test what the application does when keys disappear or a write is rejected.


Redis and DynamoDB behavior compared

Behavior Redis Open Source 8.10.3 Amazon DynamoDB
Engine and operations You operate the process or use a compatible managed service; provider defaults can differ. AWS manages the engine and physical partitions; customers choose table and index settings.
Persistence Optional RDB snapshots, AOF, both, or neither. Recovery point depends on save and fsync settings; see the Redis persistence guide. Successful writes acknowledged with HTTP 200 are durably persisted. Transactions apply within one AWS Region; see DynamoDB transaction behavior.
Reads and consistency A primary processes writes; replica reads can lag because replication is asynchronous. Table and LSI reads can be eventual or strong; GSI and stream reads are eventual. Global-table consistency depends on its configured mode; see DynamoDB read consistency.
Memory pressure maxmemory and the selected eviction policy can remove keys or reject writes. Service quotas and request capacity govern item size, throughput, and indexes; check current AWS quotas.
Scaling A single instance is bounded by its host; Redis Cluster shards keys by hash slot and has multi-key slot constraints. AWS manages data placement; design keys and indexes for access patterns and monitor throttling.

These are different operating models. RDB and AOF choices do not make Redis equivalent to DynamoDB’s managed durability, and DynamoDB’s service guarantees do not remove the need to choose consistency, indexes, capacity mode, and recovery procedures. Compare measured workload behavior and failure recovery, not a universal latency number.

For Redis persistence tradeoffs, see the RDB and AOF guide. For DynamoDB read and transaction behavior, see read consistency and transaction constraints.


Common production failures

Redis memory pressure: Reaching maxmemory triggers the configured eviction policy or write rejection. The process can also exceed the container or host memory limit because Redis needs memory beyond the dataset; the operating system may then terminate it. Leave measured headroom for overhead, forked persistence work, and clients. Test recovery from the chosen persistence and backup setup.

Unexpected Redis retention or eviction: A temporary key without a TTL can remain indefinitely. Conversely, an allkeys-* policy can evict keys the application treats as important. Set expiry where data is temporary and choose a memory policy that matches what can be reconstructed; do not treat TTL and eviction as durability controls.

DynamoDB throttling on a hot key: A test account or popular item can receive a disproportionate share of requests. Check CloudWatch throttling and consumed-capacity metrics, inspect ThrottlingReasons, and use Contributor Insights when key-level skew is unclear. Change the key design only if the required queries can use the new distribution; retry throttled requests with bounded exponential backoff and jitter. See DynamoDB throttling guidance.

AOF write latency changes: appendfsync always requests a disk sync for each write batch, while everysec and no trade different recovery points for write behavior. Measure on the actual storage and workload before choosing. Do not change the setting without checking the Redis persistence tradeoffs and recovery requirements.

A stale worker continues after a Redis lease expires: Compare-and-delete prevents one client from deleting another client’s lease, but it does not stop the old client from continuing its work. Use idempotency or a fencing token that the protected resource checks; add tests for client pauses and failover.

DynamoDB single-table design no longer fits: A table may become awkward when unrelated workloads need different retention, throughput, or index patterns. There is no useful entity-count threshold. Compare the query model and operational needs, and split tables when the separation simplifies the system.


Workload sizing worksheet

Do not estimate DynamoDB’s physical partition count from table size or a presumed per-partition ceiling. AWS manages partition placement and can change service limits. Size from the operations the application issues, current service quotas, and measured behavior under representative load.

Measure Redis Open Source 8.10.3 Amazon DynamoDB
Data shape Count keys by type; sample serialized key/value sizes and representative hashes, lists, and sorted sets. Use MEMORY USAGE and INFO memory rather than a fixed bytes-per-key constant. Count items and measure the full item size, including attribute names and values. The current maximum is 400 KB per item.
Retention Include TTL distribution, expected key churn, and how many keys remain after a normal and peak retention window. Include TTL policy and index projections; DynamoDB TTL deletion is asynchronous, so filter expired items in application reads when necessary.
Read/write demand Measure command mix, hot keys, pipeline sizes, and peak requests per second. For provisioned capacity, one RCU covers one strongly consistent read per second or two eventually consistent reads per second for an item up to 4 KB; one WCU covers one write per second for an item up to 1 KB. Transactional reads and writes consume twice those units. On-demand uses corresponding request units. Check the current capacity rules and regional service quotas.
Memory, disk, and indexes Set maxmemory below the process/container limit with room for allocator overhead, clients, and persistence forks. Track RSS, eviction/rejection counts, RDB/AOF disk use, and measured restore rate. Include GSIs, projections, and their write/read demand. Current transaction constraints are 100 unique items and 4 MB per transaction; service quotas can change, so verify the live DynamoDB constraints and quotas.
Skew and failure Load test hot keys and memory pressure; record eviction behavior, latency, snapshot duration, AOF sync behavior, replica lag, and recovery time. Test realistic key skew and bursts. Review CloudWatch consumed-capacity and throttle metrics, ThrottlingReasons, Contributor Insights, and the account/Region’s Service Quotas.

For Redis, repeat the measurements with the chosen persistence and eviction settings. The memory footprint and recovery point are properties of the data shape, Redis configuration, host, and storage. For DynamoDB, use the API’s capacity reporting and current AWS quotas; physical partition counts are not an application sizing input.


Choosing between Redis and DynamoDB

Need Redis Open Source 8.10.3 Amazon DynamoDB
Cache or ephemeral session Fits when data can be rebuilt and the eviction, persistence, and failover settings match the application’s loss tolerance. Fits when the session should survive process restarts; account for item size, TTL cleanup, and read consistency.
Durable application records Possible with RDB/AOF, backups, storage, and replication configured for the required recovery point; failover may lose acknowledged writes because replication is asynchronous. Managed durable storage; choose consistency mode, capacity, indexes, backups, and Region strategy.
Ranking or sorted access Sorted sets provide score-based ranking on a key; one hot leaderboard key remains on one Redis Cluster slot. Model bounded access through the table key or an index; a global top-N query may need a different data layout.
Coordination A TTL lease needs owner-checked release and fencing when stale work is unsafe. Conditional writes and transactions can coordinate data changes within a Region; see transaction limits.
Capacity Measure memory, command mix, persistence disk use, and host headroom. Measure item sizes, read/write units, index demand, key skew, and current account/Region quotas.

Measure latency on the chosen service, Region, client, and workload. Neither product has one useful latency number for every deployment.


Observability: Redis INFO and DynamoDB CloudWatch

For Redis, sample INFO memory, INFO stats, INFO persistence, and INFO replication. Watch dataset and RSS memory, evictions or rejected writes, keyspace hits and misses, connected and blocked clients, persistence status, and replica lag. Use SLOWLOG and latency monitoring to investigate slow commands. Compare allocator and RSS metrics with the host or container limit; a fragmentation ratio alone does not identify the cause of memory pressure.

For DynamoDB, review ConsumedReadCapacityUnits, ConsumedWriteCapacityUnits, ReadThrottleEvents, WriteThrottleEvents, ThrottledRequests, and request latency metrics in CloudWatch. Use ThrottlingReasons and Contributor Insights to investigate hot keys. These metrics indicate observed service behavior; they do not imply a fixed latency or partition count. For global tables, inspect replication metrics and the selected consistency mode. See the DynamoDB metrics guide.

Example: a feed built with write fanout

A feed can use write fanout: when an account publishes an item, a worker adds it to the feeds of active followers. Redis sorted sets or lists can serve recent entries, while a durable source of record stores the original posts. This makes reads simpler but increases writes and storage for accounts with many followers. A hybrid design can fan out to active users and assemble less-active users’ feeds on read. Measure the write amplification, retention window, and recovery path before deciding which data belongs in Redis.

Interview questions

1. Your Redis instance is using 8 GB of memory out of 10 GB max. You restart the process and memory drops to 5 GB. What happened?

Compare used_memory with used_memory_rss before and after the restart. A large difference can reflect allocator fragmentation or memory Redis does not account for as dataset memory; dirty pages are not, by themselves, an explanation for a lower Redis memory counter. Check persistence and eviction settings too, because a restart may reload a different dataset. Do not use a fixed fragmentation-ratio threshold as a diagnosis. Use Redis 8.10.3 memory stats and host/container measurements to find the source before changing allocator settings or restarting production.

2. You are using DynamoDB with a composite primary key (userId, timestamp). Your application is reading a user's data range within a time window but latency has spiked. What do you check?

Check CloudWatch consumed-capacity and throttle metrics, the exception's ThrottlingReasons, and Contributor Insights for hot-key patterns. Confirm whether the table or an index is throttling and whether the request mix or item sizes changed. Do not infer a physical partition count or blindly add random suffixes; that can make the required queries harder. If the key is genuinely hot, redesign the access pattern and load-test the new layout. Use bounded exponential backoff with jitter for retryable throttles.

3. When would you choose Redis over DynamoDB for storing session data?

Choose Redis when sessions can be recreated after eviction or a Redis outage and the team can operate the required persistence and failover setup. Choose DynamoDB when managed durability and service availability fit the recovery requirements. Neither choice guarantees a particular latency; measure it in the target Region and configuration. DynamoDB Streams can record item changes, but it is not an audit system by itself. Define which attributes must be queryable and design the table or indexes for those access patterns.

4. How does the Redis eviction policy `volatile-lru` differ from `allkeys-lru`, and when would you choose each?

volatile-lru considers only keys with an expiry; allkeys-lru considers all keys. A volatile policy does not protect non-expiring data if every key has a TTL, and writes may still be rejected when no eligible key can be evicted. Choose based on whether every key is disposable and how the application handles a miss. Redis eviction is configuration-specific; see the eviction policy guide.

5. Explain the difference between Redis replication and Redis Cluster. When would you use each?

Replication copies a primary's data to replicas asynchronously; failover behavior depends on whether Sentinel, Redis Cluster, or a managed provider coordinates promotion. A promoted replica may not have the primary's latest writes. Redis Cluster distributes the 16,384 hash slots across primaries and can use replicas for failover, but operations across keys have slot constraints. Choose based on measured data size, write distribution, recovery requirements, and the topology you can operate. Replication is not a backup.

6. Your Redis latency spikes to 100ms occasionally. What diagnostic steps do you take?

Start with Redis 8.10.3 INFO memory, stats, persistence, and replication sections, then inspect SLOWLOG GET and latency-monitoring output. Correlate spikes with evictions, rejected writes, persistence forks, replica lag, client counts, CPU, disk I/O, and host/container memory. A fragmentation ratio or operation-rate dip alone does not identify the cause. Compare command latency on the server with end-to-end client latency and check the Redis provider's telemetry if this is a managed service.

7. How do you implement a Redis rate limiter across multiple application instances?

Use an atomic script or command sequence for each counter update, then test the chosen algorithm's boundary behavior. A fixed window is simple but permits a burst around a window boundary; a sliding window or token bucket has different memory and implementation costs. A per-client key can distribute traffic only when requests are spread across clients; a single hot client key remains on one Redis Cluster slot. Local counters reduce Redis traffic but make the limit approximate across application instances. Benchmark the actual request rate and key distribution rather than targeting an unsupported requests-per-second figure.

8. Compare Redis pub/sub to Kafka for event streaming. When would you choose each?

Redis Pub/Sub does not persist messages for disconnected subscribers. Redis Streams adds persisted entries and consumer groups, but retention and recovery still depend on how the stream is managed. Kafka provides a partitioned commit log with retention and consumer offsets; delivery and durability depend on producer, broker, and consumer configuration. Choose by replay needs, retention, throughput, operational model, and required delivery semantics rather than assuming either product guarantees delivery in every setup.

9. DynamoDB has a 400KB item size limit. How do you design around this for large objects like user profiles with unbounded activity history?

Split the data according to access and retention needs. Keep a bounded profile item in DynamoDB and store large blobs in S3 with an object key in the item. Store activity records in separate items keyed for the user's range queries, or archive older records to a storage system suited to their access pattern. The current 400 KB DynamoDB item limit includes attribute names and values; verify the limit and transaction constraints in AWS's live documentation before deployment. A pointer to S3 adds another request and requires coordinated retention and access control.

10. What is the difference between Redis Strings and Redis Hashes for storing objects? When would you use each?

A string can hold a serialized object and is convenient when the application reads or replaces it as a whole. A hash lets the application read or update fields independently. Memory use depends on value shape and Redis's encoding, so compare representative data with MEMORY USAGE. Redis 8.10.3 supports hash-field expiration commands; check the hash command reference before relying on that behavior. Choose based on update/read patterns and measure memory rather than assuming one format always wins.

11. How does the Redis AOF (Append Only File) persistence work, and what are the implications for durability vs performance?

AOF records write commands and replays them during recovery. appendfsync controls when Redis requests synchronization: always syncs each write batch, everysec targets a one-second interval, and no leaves flushing to the operating system. These options trade write behavior against the possible recovery point; actual results depend on the storage and failure. Replication is asynchronous and does not guarantee that a replica has every acknowledged primary write. See the Redis persistence guide before choosing.

12. Your DynamoDB GSI is returning stale data even after writes complete. What could be causing this?

All reads from GSIs are eventually consistent; DynamoDB does not offer strongly consistent GSI reads. If the access pattern permits, read the base table or an LSI with ConsistentRead enabled. Otherwise, design the application to tolerate propagation delay and verify the current consistency behavior in the AWS documentation. Do not treat a typical propagation time as a guarantee.

13. How do you handle Redis connection exhaustion in a high-concurrency application?

Check the configured maxclients, Redis INFO clients, blocked-client counts, connection errors, and the process's file-descriptor limit. Use the client library's connection pooling or multiplexing support rather than opening one connection per request. Redis Cluster can distribute clients among nodes, but it does not remove the need to size connection pools and file descriptors for each node.

14. Explain the tradeoffs between Redis Sorted Sets and Range Queries in DynamoDB for leaderboard implementations.

A Redis sorted set orders members for one key and supports rank and range commands. DynamoDB can query an ordered range when the sort key and partition key match the access pattern, but a global top-N across unrelated partition keys needs a different design, often a GSI or precomputed partitions. Compare update rate, query scope, item retention, and recovery needs. Measure both designs on representative data instead of assuming one is always faster.

15. What is Redis pipelining, how can it affect throughput, and what are the caveats?

Pipelining lets a client send several commands before waiting for replies, reducing round trips. The commands are still processed individually and the pipeline is not an atomic transaction. A client cannot use an earlier reply to construct a later command in the same batch. Very large batches use client and server memory and can delay other work, so benchmark batch sizes against response time and memory for the actual workload.

16. How would you design a Redis-based cache warming strategy for a new application deployment?

Warm only data that is likely to be requested soon and fits the memory budget. Use recent access metrics to choose a candidate set, load it in bounded batches, and keep a lazy cache-aside path for the rest. Monitor hits, misses, memory, and origin load after rollout. There is no universal number of entries to preload; choose from measured item sizes and access patterns.

17. DynamoDB On-Demand vs Provisioned capacity: when would you choose each, and how do you handle cost optimization?

On-demand mode bills for requests and adjusts capacity without setting a provisioned read/write target; provisioned mode reserves capacity and can use auto scaling. Compare current regional pricing, request patterns, burst behavior, quotas, and index costs. Use CloudWatch consumed-capacity and throttling metrics to set alarms from the workload's error budget; there is no universal utilization target. Check AWS's current capacity-mode documentation before making a cost estimate.

18. What is the difference between Redis BITCOUNT and HyperLogLog for cardinality estimation?

BITCOUNT exactly counts set bits in a string. If you hash entity IDs to bit positions, collisions mean the result is not an exact distinct-entity count. Redis HyperLogLog estimates distinct cardinality with a standard error of about 0.81%; its dense representation uses about 12 KB, while sparse encoding can use less for smaller sets. Use a bitmap when the key space is bounded and you can manage collisions, or HyperLogLog when an approximate distinct count is acceptable. See the Redis HyperLogLog guide.

19. How do you handle cross-region Redis replication for disaster recovery?

Redis Open Source replication and Cluster are not the same as a managed provider's cross-region active-active product. Check the exact product and topology rather than assuming a feature named geo-replication is available in Redis OSS. DynamoDB global tables offer configured multi-Region consistency modes; their behavior and transaction scope differ by mode. Write down the required recovery point and recovery time, then test failover and measure replication lag. For DynamoDB, see global-table consistency.

20. Your Redis cluster is experiencing split-brain after a network partition. How do you diagnose and resolve it?

Check CLUSTER INFO and CLUSTER NODES on reachable nodes, then compare slot ownership, node flags, replication links, and application write errors. Redis Cluster uses quorum and failure-detection settings; during a partition, some nodes can stop accepting writes, and a promoted replica may not contain every recent write. Do not assume the largest network partition automatically wins or that divergent writes merge. Restore connectivity, consult the Redis Cluster specification, inspect data consistency, and use the supported resynchronization procedure for the deployed version. Take backups before manual slot or failover changes.

Further reading

For more on NoSQL databases, see the NoSQL overview. To learn about caching strategies, see Caching Strategies. For comparison with Redis and Memcached, see Redis vs Memcached.

Conclusion

Redis and DynamoDB both serve key-based access patterns, with different operating models. Redis can keep ephemeral or frequently accessed data in memory, with persistence, replication, and eviction behavior set by the deployment. DynamoDB provides managed storage with documented read consistency options and service quotas. Measure latency and recovery behavior in the intended Region and configuration before choosing.

Start with the reads and writes the application needs, then choose keys, indexes, retention, consistency, and recovery settings to support them. Check DynamoDB’s current constraints and quotas during capacity planning, and test Redis’s persistence, eviction, and failover behavior against the data-loss tolerance.

Category

Related Posts

Redis vs Memcached: Choosing an In-Memory Data Store

A comprehensive comparison of Redis and Memcached — data structures, persistence, clustering, Lua scripting, pub/sub, and guidance on when to choose each.

#system-design #databases #caching

Column-Family Databases: Cassandra and HBase Architecture

Cassandra and HBase data storage explained. Learn partition key design, column families, time-series modeling, and consistency tradeoffs.

#database #nosql #column-family

Document Databases: MongoDB and CouchDB Data Modeling

Compare MongoDB and CouchDB data modeling, transactions, consistency settings, and replication behavior with relational databases.

#database #nosql #document-database