Scrivio Interview library
CodingIntermediate6 min read · updated 13 November 2026

A link-shortening service maps 200 million numeric short ids to numeric target ids in Redis. Stored as one string key per id, the instance uses about 16 GB, mostly per-key overhead rather than data.

Show how bucketing into small hashes reduces memory, with the key scheme and commands, and explain what you give up.

Instead of one string key per id, we group ids into buckets of 1,000 and store each bucket as a small hash: id 1234567 becomes HSET l:1234 567 98765. Each bucket stays a listpack, so an entry costs a few bytes instead of 60 to 80 bytes of per-key overhead, which can shrink 16 GB to a few GB. We give up per-entry TTLs (unless we use hash field expiration), eviction of single entries and some CPU per lookup, and the application now owns the key scheme.

Why this question is asked

This is the textbook memory trick for Redis, and interviewers like it because it tests whether we understand where Redis memory really goes. With 200 million tiny values, the data itself is almost nothing; the cost is the bookkeeping Redis keeps for every top-level key. In this answer, we will look at what one key costs, build the bucketing scheme with real commands and code, estimate and measure the saving, and then go carefully through what we give up and how it behaves in Redis Cluster.

1What One Top-Level Key Costs

When we SET l:1234567 98765, Redis creates several things. The keyspace is a dictionary, so there is a dictionary entry pointing to the key and the value. The key is a separate string allocation, with a small header. The value is a Redis object, and here the integer fits inside it, but the object header still takes 16 bytes. The dictionary's bucket array needs a slot too, and the allocator rounds every allocation up to its size class.

Added together, that is often 50 to 70 bytes per key before any data, and if the key has a TTL there is a second entry in the expires dictionary. For 200 million keys, 60 to 80 bytes each gives the 12 to 16 GB we see, while the actual numbers would fit in under 2 GB.

2The Bucketing Scheme

The idea is to have far fewer top-level keys, each holding many entries in a compact form. We divide the id by 1,000 to get the bucket number and use the remainder as the field. Id 1234567 goes into bucket l:1234 as field 567. Ids 1234000 to 1234999 all share that one key.

Text
# One key per id (before)
SET l:1234567 98765 -- OK
GET l:1234567 -- "98765"
# Bucketed (after): bucket = id / 1000, field = id % 1000
CONFIG SET hash-max-listpack-entries 1024 # each bucket holds up to 1000 fields
HSET l:1234 567 98765 -- (integer) 1
HGET l:1234 567 -- "98765"
OBJECT ENCODING l:1234 -- "listpack"

The limit has to be raised, because the default of 128 entries would convert a full bucket to a hashtable and lose the saving. Field and value are short integers, far below the 64-byte value limit. The bucket size of 1,000 is a choice, not a law; it should be benchmarked, because each lookup scans the listpack.

3The Same Thing in Java

In a Spring application the scheme lives in one small class, so no caller ever builds the key by hand.

Java
@Component
class ShortLinkStore {
private final StringRedisTemplate redis;
ShortLinkStore(StringRedisTemplate redis) { this.redis = redis; }
private static String bucket(long id) { return "l:" + (id / 1000); }
private static String field(long id) { return Long.toString(id % 1000); }
void put(long id, long target) {
redis.opsForHash().put(bucket(id), field(id), Long.toString(target));
}
Long get(long id) {
Object v = redis.opsForHash().get(bucket(id), field(id));
return v == null ? null : Long.valueOf(v.toString());
}
}
// store.put(1234567L, 98765L); -> HSET l:1234 567 98765
// store.get(1234567L) -> 98765
// store.get(1234568L) -> null

Using StringRedisTemplate matters here. With the default JDK serializer, keys and values would be stored as serialized Java objects of dozens of bytes, which would break the listpack value limit and waste the saving.

4Estimating and Measuring the Saving

In the listpack, a small integer field such as 567 takes about 3 bytes and a value such as 98765 about 5, so an entry costs around 8 bytes. 200 million entries is about 1.6 GB, and 200,000 bucket keys add a few tens of megabytes of key overhead. Compared with 16 GB, that is a several-fold saving.

Estimates are only a start. We should load a realistic sample, say 10 million ids, both ways on a test instance and compare used_memory from INFO memory, and use MEMORY USAGE on a few full buckets to check that they are listpacks of the expected size. Savings of five to ten times are common for this pattern, but the real number depends on the data.

One key per id versus buckets of 1,000
String key per idHash bucket per 1,000 ids
Top-level keys200 million200 thousand
Cost per entryabout 60-80 bytesabout 8 bytes in a listpack
Approximate memoryabout 16 GBabout 2 GB
TTL per entryyesonly with HEXPIRE (Redis 7.4+)
Lookup costO(1) hash lookupscan up to 1,000 entries
Numbers are estimates for small integer ids and values; measure with a sample.

5What We Give Up

First, expiry. A TTL belongs to a key, so all entries in a bucket share one. If links need individual expiry, we need hash field expiration with HEXPIRE, available from Redis 7.4 (check your engine and version), and note that a field with a TTL may change how the hash is stored. Second, eviction: if this is a cache under maxmemory, Redis evicts whole buckets, removing 1,000 links at once.

Third, CPU. A lookup in a 1,000-entry listpack scans up to a few kilobytes, which is still fast, but measurably slower than a direct key lookup; on a busy instance we should check p99. Fourth, the application owns the scheme: every reader and writer must use the same bucket function, and tools that inspect keys now see buckets.

In Redis Cluster nothing breaks. Each bucket is still an ordinary key, so the 200,000 buckets hash to different slots and spread across the shards like any other keys. We just must not put a shared hash tag in the bucket name, which would pull them all into one slot.

6Follow-up questions

Why not raise the entry limit to 100,000 and use even fewer keys?

Because every operation on a listpack scans and can reallocate the whole array. A 100,000-entry bucket would be about a megabyte, so an HGET would scan up to that much and an HSET that grows it could copy it, turning a microsecond command into a millisecond one that blocks the main thread. The per-key overhead is already negligible at 1,000 entries, so going further buys almost nothing and costs a lot of latency.

Would a sorted set or a plain string with offsets work too?

A string addressed with GETRANGE and SETRANGE at fixed offsets can be even smaller for dense fixed-width ids, but it is harder to maintain and cannot express missing entries cleanly. A sorted set is larger than a hash for this use. The hash bucket is the usual balance of compactness and simplicity.

How do we migrate without downtime?

Write to both layouts, have readers try the bucket first and fall back to the old key, backfill the buckets with a SCAN-driven job, then switch readers and delete the old keys with UNLINK in batches.

7Conclusion

In this answer, we saw that 200 million tiny string keys cost mostly per-key overhead, 50 to 70 bytes or more each, and that grouping ids into hash buckets of about 1,000 that stay listpacks cuts the cost per entry to a few bytes. We wrote the key scheme, raised hash-max-listpack-entries, and measured with MEMORY USAGE and INFO memory. The trade is no per-entry TTL without HEXPIRE, eviction of whole buckets, more CPU per lookup and a scheme the application must own, while Redis Cluster keeps working because each bucket is its own key.

What to say in the interviewAbout 80 seconds aloud

Open with

With one key per id, almost all of the 16 GB is per-key overhead: a dictionary entry, a key string, an object header and allocator rounding, often 50 to 70 bytes before the data, plus an expires entry if there is a TTL.

Then, if they want more

So I would bucket the ids. For id 1234567 the key is l: plus id divided by 1000, so l:1234, and the field is id mod 1000, so HSET l:1234 567 98765 and HGET l:1234 567. I raise hash-max-listpack-entries to about 1,000, after benchmarking, so each bucket stays a listpack, and then an entry costs a few bytes.

I would use a string serializer so values stay small. I would expect several-fold savings, but I would prove it by loading a realistic sample and comparing INFO memory and MEMORY USAGE on a few buckets.

What I give up: no TTL per entry unless the engine supports hash field expiration, which is HEXPIRE from Redis 7.4; eviction drops whole buckets; lookups scan a larger listpack, so slightly more CPU; and the application owns the key scheme. In Redis Cluster it still works, because every bucket is its own key and they spread across slots.

About this answer

Last updated
13 November 2026
Versions it names
Redis 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how bucketing into small hashes reduces memory, with the key scheme and commands...": https://scrivio-interview-library.netlify.app/databases/redis-internals/3dc4b5d038/