Core Data Structures
Strings, hashes, lists, sets, sorted sets and Redis 8's JSON, time series and vector sets, plus the encodings underneath. Interviewers check that you pick a type by its commands and memory cost.
part ofRedisread it →on this pageshowhide
explore
- Strings & Bitmaps6 questions
- Hashes6 questions
- Lists4 questions
- Sets5 questions
- Sorted Sets6 questions
- HyperLogLog4 questions
- Geospatial Indexes5 questions
- Internal Encodings6 questions
- JSON Type6 questions
- Time Series Samples6 questions
- Bloom, Cuckoo & Top-K6 questions
- Vector Sets6 questions
questions
66 · 12 sectionsThe Redis SET command accepts NX, XX, EX/PX, KEEPTTL and GET options. What does each of them do, and why is `SET key value NX EX 30` preferred over calling SETNX and then EXPIRE?
basics
~20 sNX writes only if the key is absent, XX only if it already exists, EX/PX attach a TTL in seconds/milliseconds, KEEPTTL keeps the current TTL, GET returns the previous value. A single SET is one atomic command; SETNX then EXPIRE can leave a key with no TTL if the client dies between them.
Why is Redis's INCR the correct way to implement a counter shared by many clients, and what happens if the key is missing, holds non-numeric text, or is incremented past the 64-bit range?
basics
~20 sINCR performs the read-modify-write inside Redis as one command, so concurrent clients cannot lose updates. A missing key is treated as 0 and created. A non-numeric or out-of-range value returns an error rather than resetting. Values are signed 64-bit; overflow errors instead of wrapping. INCR keeps any existing TTL.
Redis has no dedicated bitmap type — SETBIT, GETBIT and BITCOUNT operate on ordinary strings. How does that work, how much memory does a daily-active-user flag for 50 million user ids cost, and what is the trap when the bit offsets are sparse?
basics
~20 sA bitmap is just a string addressed bit by bit. SETBIT key offset 0|1 sets a bit and returns the old one; BITCOUNT counts set bits. 50 million bits is about 6 MB. The trap: setting a high offset allocates every byte below it, so a single sparse id can allocate hundreds of MB.
Redis strings can be modified in place with APPEND, SETRANGE and read partially with GETRANGE. How do these commands behave — including what SETRANGE does when you write past the end of the value — and what are the limits of treating a Redis string as a growable buffer?
basics
~20 sA Redis string is a mutable byte array. APPEND adds bytes to the end and returns the new length. SETRANGE overwrites bytes at an offset, zero-filling any gap. GETRANGE returns a byte slice and accepts negative indexes. Max length is 512 MB, and rewriting huge values gets expensive.
Redis's BITFIELD command lets you treat a string as an array of arbitrary-width integers with u8, i5 or similar types. When is that worth using instead of ordinary keys, and what do the OVERFLOW WRAP, SAT and FAIL modes control?
basics
~20 sBITFIELD packs many small integers into one string, addressed by bit offset and width (u1..u63, i1..i64). It runs GET/SET/INCRBY operations atomically in one command. OVERFLOW chooses what happens on wrap: WRAP wraps around, SAT clamps at the limit, FAIL returns nil and skips the write.
How would you store a user profile in a Redis hash, and which commands read a single attribute, several attributes, and the whole object? What happens to the key when you delete its last field?
basics
~20 sHSET user:42 name Ada email [email protected] writes fields; HGET reads one, HMGET reads several in one call, HGETALL returns every field and value. HDEL removes fields, and when the last field goes the key itself is deleted — Redis has no empty hashes.
When storing an object in Redis, what do you gain and lose by modelling it as a hash with one field per attribute versus serialising the whole object to JSON and storing it in a single string key?
basics
~20 sA hash gives partial reads and writes (HGET/HSET one field), atomic per-field updates like HINCRBY, and compact memory for small objects. A JSON string gives one round trip, nesting and arrays, and atomic whole-object replacement — but every update is a read-modify-write that can lose concurrent changes.
You are keeping per-endpoint request counters grouped under one Redis key. How does HINCRBY behave when the key or the field does not exist yet, when the stored value is not a number, and how does it compare with reading the field and writing it back from the application?
basics
~20 sHINCRBY treats a missing key or field as 0, creates it, and returns the new value. It errors if the value is not a 64-bit integer or if the result would overflow. It is one atomic command, so unlike HGET-then-HSET it cannot lose concurrent increments.
You want to show a random sample of fields from a large Redis hash without pulling the whole thing. How does the Redis command HRANDFIELD serve that, how does its reply shape change with the WITHVALUES option under RESP2 versus RESP3, and how does it compare with HSCAN for the same job?
basics
~20 sHRANDFIELD key count returns random field names at O(count) cost, independent of how big the hash is. WITHVALUES adds each value: a flat field,value,field,value array under RESP2, a map under RESP3. It samples; HSCAN enumerates the whole hash. Its order is not pagination.
Redis 7.4 added the HEXPIRE command family. What problem does expiring individual hash fields solve, how do you use those commands, and how did teams handle the same requirement before they existed?
basics
~20 sBefore 7.4, TTL applied only to a whole key, so one stale attribute forced you to expire the entire object. HEXPIRE key ttl FIELDS numfields f1 f2 sets a TTL per field; HTTL reads it, HPERSIST clears it, and the key is deleted when its last field expires. Older workarounds: one key per field, or a timestamp index swept by a job.
Describe the Redis List type: which commands you use to add and remove elements, how you read a range out of it, and how the cost of those operations differs between the ends of the list and the middle.
basics
~20 sAn ordered sequence of strings with fast ends. LPUSH/RPUSH add at head/tail, LPOP/RPOP remove there, all O(1). LRANGE reads a slice; LINDEX/LSET/LINSERT/LREM touch the middle and are O(N) because Redis walks the list. Duplicates are allowed, order is insertion order, and an emptied list key is deleted.
Redis offers blocking list commands such as BLPOP and BLMOVE. Explain what blocking means here, what happens to the server and to other clients while one client is blocked, and how these commands behave inside a MULTI/EXEC transaction.
basics
~20 sBLPOP parks the calling client until an element arrives on one of the given keys or the timeout expires, returning key and value, or nil on timeout. Only that client waits; the server keeps serving everyone else. Inside MULTI/EXEC and Lua they never block — they behave like the non-blocking version and return nil immediately.
You want a Redis key holding only the 100 most recent events for each user, without it growing forever. Show how LPUSH together with LTRIM implements that, and explain what the trim actually costs and why the two commands should be issued together.
basics
~20 sPush then trim: LPUSH feed:42 event, then LTRIM feed:42 0 99, which keeps only that index range and discards the rest. Send both in one MULTI/EXEC or Lua script so the list is never read oversized and the trim cannot be skipped. LTRIM is O(N) in elements removed, so trimming on every push removes about one element.
A worker pops a job from a Redis list with LPOP and crashes while processing it. Describe how the LMOVE and BLMOVE commands let you build a queue that survives this, and what that design still leaves you to handle yourself.
basics
~20 sWith LPOP the job is gone the moment it is delivered, so a crash loses it. Instead use BLMOVE queue processing:<worker> LEFT RIGHT: it atomically pops and appends to a per-worker processing list, so the job stays visible. Remove it with LREM after success. You must still write the reaper for orphaned entries and make handlers idempotent.
What is a Redis Set, and which commands do you use to add a member, remove one, test membership and get the element count?
basics
~20 sA Set is an unordered collection of unique strings. SADD adds (duplicates are silently ignored), SREM removes, SISMEMBER tests membership, SCARD returns the size, SMEMBERS returns everything. Add, remove, membership test and count are all O(1).
A Redis Set holds several million members. What does SMEMBERS cost the server and the client, and how would you satisfy the common requests against that set — its size, whether specific values are in it, a random sample, the size of its overlap with another set — without ever materialising it?
basics
~20 sSMEMBERS is O(N): one giant reply that occupies the single command thread and can blow the client output buffer, killing the connection. Ask set-native questions instead — SCARD for size, SISMEMBER/SMISMEMBER for membership, SRANDMEMBER for a sample, SINTERCARD with LIMIT for overlap size.
Redis offers SINTER, SUNION and SDIFF plus SINTERSTORE, SUNIONSTORE and SDIFFSTORE. How do these behave, what do they cost, and when would you reach for the STORE variants?
basics
~20 sThey compute intersection, union and difference of Sets on the server. SINTER is roughly O(smallest set × number of sets), SUNION/SDIFF O(total members). STORE variants write the result into a destination key and return its size instead of shipping members — the destination is overwritten and gets no TTL.
Redis has both SPOP and SRANDMEMBER for getting random elements out of a Set. How do they differ, and how does supplying a count — including a negative one — change what you get back?
basics
~20 sSPOP removes and returns random members; SRANDMEMBER returns them without removing. With a positive count both return distinct members, capped at the set size. Only SRANDMEMBER accepts a negative count, which allows repeats and returns exactly that many elements.
You are designing catalog filtering by multiple tags on top of Redis Sets — users pick several tags and see the matching items. How would you model it, and what breaks as the catalog and tag cardinalities grow?
basics
~20 sModel one Set per tag holding item ids, plus a reverse Set per item for maintenance. AND is SINTER, OR is SUNION, exclusion SDIFF. It degrades when every selected tag is huge: the work happens in one blocking command. Mitigate with selective-tag ordering, SINTERCARD LIMIT, SINTERSTORE into short-TTL result keys, and precomputed hot combinations.
What is a Redis Sorted Set, how is the ordering of its elements defined, and which commands do you use to add an element, read its score, read its rank and read a range?
basics
~20 sA Sorted Set holds unique string members, each with a floating-point score, kept ordered by score ascending and by member bytes when scores tie. ZADD adds or updates, ZSCORE reads a score, ZRANK gives the 0-based position, ZRANGE reads a slice, ZCARD counts.
Design a game leaderboard on Redis Sorted Sets: how do you record a score change, fetch the top ten, and show one player their own position and the players around them?
basics
~20 sStore one Sorted Set of player→score. Record with ZINCRBY for deltas or ZADD GT for high-water marks. Top ten is ZRANGE key 0 9 REV WITHSCORES. A player's position is ZREVRANK (0-based, add 1 for display), and neighbours are a small ZRANGE REV around that rank.
Implement a sliding-window rate limiter using a Redis Sorted Set — which commands run, in what order, and what are the failure modes you have to design around?
basics
~20 sPer subject, keep a Sorted Set whose scores are request timestamps. On each request: ZREMRANGEBYSCORE to drop entries older than the window, ZCARD to count, ZADD a uniquely-named entry if under the limit, and PEXPIRE the key. Run all four atomically in one Lua script.
Explain the ZADD flags NX, XX, GT, LT, CH and INCR in Redis, and give a situation where each one changes the outcome.
basics
~20 sNX only inserts new members, XX only updates existing ones, GT and LT update only if the new score is greater or lesser. CH changes the reply to count added-or-changed members. INCR makes ZADD behave like ZINCRBY and return the new score, or nil if a condition blocked it.
A leaderboard in Redis holds tens of millions of players and product now wants every player's exact global position plus deep pagination through the standings. Which parts of that stay cheap, which do not, and how would you architect around the limits?
basics
~20 sExact rank and top-N stay cheap — both are O(log N). Deep pagination by index is not: cost grows with the offset. Memory and single-key hotness are the real ceilings. Paginate by score cursor, serve reads from replicas, shard into cohort boards, and approximate global rank with score-bucket counters.
You keep one Redis HyperLogLog per day of unique visitors. How do you produce a weekly and a monthly unique-visitor number, and what does the PFMERGE command guarantee about the accuracy of the result?
basics
~20 sUnion the daily keys: PFCOUNT day1 day2 ... estimates the union directly, or PFMERGE week day1 day2 ... stores a reusable weekly key. Merging takes the max of each register, so the merged key equals one built from all raw elements; error stays ~0.81% and does not accumulate across merges.
Redis exposes a HyperLogLog type through the PFADD and PFCOUNT commands. What problem does it solve, and what do you give up compared with putting the same items into a Redis Set and calling SCARD?
basics
~20 sIt counts unique items approximately in fixed memory. PFADD adds an element; PFCOUNT returns an estimated distinct count with about 0.81% standard error, using at most ~12 KB per key however many items you add. Unlike a Set it stores no members, so you cannot list them, test membership, or remove one.
Redis documents a standard error of about 0.81% and a footprint of about 12 KB for a HyperLogLog. What do those two numbers actually mean for a counter tracking roughly 50 million uniques, and why is a freshly created key far smaller than 12 KB?
basics
~20 s0.81% is a standard deviation, not a bound: at 50 million uniques a typical estimate is off by ~400k, and a couple of percent happens. 12 KB is the dense form of 16384 six-bit registers; small keys use a compact sparse encoding and convert to dense once they exceed hll-sparse-max-bytes, irreversibly.
Product wants unique-user counts sliced by page, country and hour, and also wants to answer 'has user X visited this page?' and 'how many users saw both page A and page B?'. How do you decide which of these Redis HyperLogLog can serve, and what do you use for the rest?
basics
~20 sHyperLogLog serves only the sliced counts, via one key per slice plus PFMERGE rollups. Membership and intersection are impossible with it: no per-element test, no PFINTERSECT, and inclusion-exclusion is numerically useless. Serve those with Sets, bitmaps over dense user IDs, or an offline store, and budget ~12 KB per dense slice key.
A ride-hailing backend needs to find every driver within 5 km of a pickup point using Redis. Which Redis commands would you use to store the driver positions and to run that proximity query, and what does the query return?
basics
~20 sGEOADD drivers <longitude> <latitude> <driverId> stores each position (longitude first). GEOSEARCH drivers FROMLONLAT <lon> <lat> BYRADIUS 5 km ASC WITHDIST returns the member names inside the circle, nearest first, with distances. Re-run GEOADD to move a driver.
Redis geospatial commands are often described as a thin layer over another core Redis type. Which type actually backs GEOADD, how is a longitude/latitude pair encoded into it, and what practical consequences does that have for how you operate the key?
basics
~20 sA sorted set. GEOADD interleaves 26 bits of longitude and 26 bits of latitude into one 52-bit geohash integer and stores it as the member's score. So ZREM, ZSCORE, ZCARD, ZRANGE, DUMP and EXPIRE all work on a geo key, and nearby-search is a set of score-range scans.
Redis 6.2 introduced the GEOSEARCH and GEOSEARCHSTORE commands and deprecated the older GEORADIUS family. What do the newer commands add, and why could the original GEORADIUS not be executed on a read-only replica?
basics
~20 sGEOSEARCH unifies GEORADIUS and GEORADIUSBYMEMBER (FROMLONLAT or FROMMEMBER) and adds rectangle search with BYBOX. GEORADIUS had an optional STORE clause, so Redis classified it as a write command and replicas refused it — hence the separate GEORADIUS_RO. GEOSEARCH is read-only; GEOSEARCHSTORE is the writing variant.
What accuracy and coverage limits apply to Redis geospatial indexes — how exact are the coordinates returned by GEOPOS and the distances returned by GEODIST, and which coordinates cannot be stored at all?
basics
~20 sCoordinates are quantised to 26 bits per axis, so GEOPOS comes back within roughly a metre of what you wrote, never bit-identical. GEODIST is a great-circle distance on a sphere — a straight line, no roads, no altitude, with sub-percent error. Latitude is limited to about ±85.05°, so the poles cannot be stored.
You are designing a 'vehicles near me' lookup on Redis Cluster for a fleet of two million vehicles that report their position every few seconds. How would you lay out the geospatial keys, and what specifically breaks if you keep every vehicle in a single key?
basics
~20 sOne key lives in one hash slot on one shard, so a single global index pins every position write and every query to one core, and dense-area queries scan huge candidate sets. Partition by region (geo:{city}) or geohash-prefix cell, fan out to neighbouring cells client-side, and sweep stale members with ZREM since geo members have no TTL.
Running OBJECT ENCODING on a small Redis hash returns "listpack", and on a large one it returns "hashtable". What is that command reporting, and why does Redis keep more than one internal representation for the same data type?
basics
~20 sOBJECT ENCODING reports the internal memory layout Redis chose for that value. Small collections use a compact, cache-friendly flat array (listpack/intset) that saves a lot of memory; once they grow past configured thresholds Redis switches to a real hash table or skiplist for O(1)/O(log n) access.
Which Redis configuration settings decide whether a hash or sorted set keeps its compact internal layout, and what exactly happens at the boundary?
basics
~20 shash-max-listpack-entries / hash-max-listpack-value and zset-max-listpack-entries / zset-max-listpack-value, defaulting to 128 entries and 64 bytes. Exceeding either — too many entries, or one element longer than the value limit — converts the value to hashtable or skiplist, permanently.
When a Redis sorted set grows past its compact threshold, OBJECT ENCODING reports "skiplist". What two structures does that encoding actually maintain, and why does it need both?
basics
~20 sIt keeps a skiplist ordering members by score for O(log n) rank and range queries, plus a hash table mapping member to score for O(1) lookups and updates. Neither structure alone gives both ordered access and constant-time member lookup.
A Redis instance holds 50 million tiny key-value pairs and uses far more memory than the sum of the values suggests. How would you investigate, and what restructuring would let the encoding layer cut that footprint?
basics
~20 sEach top-level key carries its own object, SDS and dict-entry overhead — often 50-100 bytes regardless of value size. Group the records into hashes bucketed so each stays under hash-max-listpack-entries/value, so many records share one compact listpack. Measure with MEMORY USAGE, OBJECT ENCODING and MEMORY DOCTOR.
A Redis list of a million elements reports the "quicklist" encoding while a three-element list reports "listpack". Explain how a quicklist is built and what list-max-listpack-size and list-compress-depth control.
basics
~20 sA quicklist is a doubly linked list whose nodes are each a listpack holding many elements. list-max-listpack-size caps a node by element count (positive) or by bytes (negative, e.g. -2 = 8 KB). list-compress-depth LZF-compresses interior nodes, leaving that many nodes uncompressed at each end.
In Redis 8, what is the JSON data type, and which commands create a document and read it back?
basics
~20 sThe Redis JSON type stores a parsed document as a binary tree under one key, part of Redis Open Source since 8.0. JSON.SET creates or changes it, JSON.GET reads any path, and JSON.MGET reads one path across keys.
A cart stored as a serialized string under one Redis key is updated by several services; how do `JSON.NUMINCRBY`, `JSON.ARRAPPEND` and `JSON.DEL` change that?
basics
~20 sEach command changes one part of the document inside the server as one atomic step, so services stop overwriting each other's read-modify-write cycles. Only the change travels, though an invariant spanning several commands still needs a transaction.
In Redis's JSON commands, how does a JSONPath `$` path differ from a legacy `.` path in what it matches and replies?
basics
~20 sIn Redis JSON commands, a JSONPath such as $.a returns every match wrapped in an array, and an empty array on a miss. A legacy path such as .a reads the first match as a bare value and errors on a miss.
After moving carts from serialized strings to the Redis JSON type, memory use grew sharply; how do you measure the per-document cost and explain the growth?
basics
~20 sA Redis JSON document is a tree, so each value costs at least 8 bytes on 64-bit and arrays reserve spare capacity. JSON.DEBUG MEMORY and MEMORY USAGE read one key but over-count reused strings, so confirm with used_memory on real data.
After moving carts to the Redis JSON type, `JSON.NUMINCRBY` calls report no error, yet some quantities never change and other lines get the increment; how do you diagnose it?
basics
~20 sRead the replies: with a $ path, no match returns an empty array and a non-number returns null, and neither is an error. Increments on the wrong line point to positional paths like $.items[2] after another service's delete shifted the array.
In Redis's time series type, what does a series hold, and how do TS.CREATE and TS.ADD build one with retention and labels?
basics
~20 sA Redis time series is one key of millisecond timestamps paired with double values. TS.CREATE makes it empty with RETENTION and LABELS; TS.ADD appends a sample, creates a missing key, and replies with the timestamp.
In Redis, how do you use TS.CREATERULE to keep raw time series samples for a day and a downsampled series for a year?
basics
~20 sCreate a destination series first, with its own RETENTION, then run TS.CREATERULE source dest AGGREGATION avg 60000. Give raw a day's retention and the destination a year's. Only samples added after the rule are aggregated.
In a Redis time series, what happens when TS.ADD repeats an existing timestamp, and how do DUPLICATE_POLICY and ON_DUPLICATE control the outcome?
basics
~10 sBy default the second sample fails: DUPLICATE_POLICY is BLOCK and TS.ADD replies with an error. A series can instead keep FIRST, LAST, MIN, MAX or SUM, and ON_DUPLICATE overrides that policy for one command.
For a fleet dashboard on Redis time series, how do TS.RANGE with AGGREGATION and TS.MRANGE with FILTER and GROUPBY differ, and what do they reply?
basics
~20 sTS.RANGE reads one key and can bucket it with AGGREGATION, replying with timestamp and value pairs. TS.MRANGE finds series by a label FILTER, replies per series, and GROUPBY with REDUCE combines same-timestamp values across each group.
Devices in a Redis time series fleet upload buffered readings after hours offline; ingest slows, some writes fail and hourly rollups look wrong. How do you diagnose and fix it?
basics
~20 sLate samples take the upsert path: each rewrites a compressed chunk and each rule recomputes its bucket. Samples beyond retention are rejected, and partly trimmed buckets get overwritten. Replay oldest first and keep raw retention above lateness plus bucket.
With Redis BF.RESERVE, what do error_rate, capacity, EXPANSION and NONSCALING decide for a sign-up username filter, and what do BF.ADD and BF.EXISTS replies mean?
basics
~20 sBF.RESERVE key error_rate capacity sets the false-positive target and expected items; EXPANSION sizes extra sub-filters and NONSCALING forbids them. BF.ADD replies 1 if new, 0 if probably present. BF.EXISTS 1 means probably added; 0 means not added, or no such key.
Redis Top-K and t-digest keys have no time window, so how do you serve a last-hour trending panel and a last-hour latency percentile from them?
basics
~20 sNeither key has a clock: Top-K decay reacts to collisions, not time, and t-digest observations cannot be removed. Use one key per time bucket with EXPIRE. TDIGEST.MERGE combines buckets, but Top-K has no merge command, so stagger its sketches.
In Redis 8, which probabilistic structure fits a username check, per-card counts, a trending panel and latency percentiles, and how does each one err?
basics
~20 sUse Bloom for the username check, count-min for per-card counts, top-k for trending and t-digest for percentiles. Bloom can falsely say yes, count-min over-counts, top-k can miss or misrank items, and t-digest returns an estimate.
A Redis cuckoo filter of unused coupon codes starts rejecting valid codes after weeks of CF.DEL calls: what went wrong, and how do you repair and prevent it?
basics
~20 sCF.DEL removes a matching fingerprint, not the item. Deleting a code that was never added, or deleting one twice, can erase another code's fingerprint, causing false negatives. Rebuild the filter from the database and delete only after it confirms the code.
When should a team accept a Redis Bloom, count-min, top-k or t-digest answer in a user-visible feature, and what standing rules does a lead set first?
basics
~20 sAccept one when a wrong answer is cheap or an exact store can confirm it, and an exact structure costs too much. First require a stated error direction, explicit sizing, a rebuild path and a plan for losing the key.
What is a Redis vector set, and how do VADD and VSIM add elements and find the most similar ones?
basics
~20 sA vector set is a Redis key holding unique string elements, each paired with an embedding instead of a score. VADD inserts an element and its vector; VSIM returns the elements most similar to a given vector or element.
In a Redis vector set, what do VADD's Q8, BIN and NOQUANT options trade, and what does REDUCE add on top?
basics
~20 sQuantization trades recall for memory and speed: Q8, the default, stores one byte per component, BIN one bit, and NOQUANT a full float. REDUCE also cuts the component count by projection. All are fixed when the key is created.
In Redis, how does a vector set differ from a VECTOR field in an FT.CREATE index, and when does each one fit?
basics
~20 sA vector set is one key holding its own elements, graph and JSON attributes, with cosine ranking. A VECTOR field indexes vectors stored in hash or JSON documents and combines them with text, tag and numeric fields in queries.
A Redis VSIM call with FILTER and COUNT 10 returns only three elements although more should match: how do you diagnose and fix it?
basics
~20 sEither the search hit its effort cap, COUNT times 100 candidates by default, or the attributes do not match as you think. Compare against the same query with TRUTH, inspect attributes with VGETATTR, then raise FILTER-EF or split the set.
A support bot's semantic cache in a Redis vector set serves wrong answers and keeps growing: how do you fix the similarity check and retire old entries?
basics
~20 sVSIM scores rescale cosine from -1..1 to 0..1, so EPSILON 0.1 accepts cosine 0.8, not 0.9; tighten it. Elements have no TTL, so track age yourself and call VREM, because dropping or evicting the key removes everything at once.