Why one thread is fast
io-threads 4Commands still run on the main thread.TrapOne slow command, like KEYS or a DEL of a huge value, blocks every client.
Asked in interviews
AskedWhy is Redis fast even though it runs commands on a single thread?maxmemory, the eviction policy deletes keys, or the default noeviction rejects writes.io-threads 4Commands still run on the main thread.TrapOne slow command, like KEYS or a DEL of a huge value, blocks every client.
Asked in interviews
AskedWhy is Redis fast even though it runs commands on a single thread?TrapDon't say Redis loses its data on restart. RDB snapshots and the AOF reload it.
JSON.SET user:1 $ '{"name":"Ann"}'FT.SEARCH idx "action"Before Redis 8, you loaded these as modules.TrapRunning Redis for your own company is allowed under every license. The limits are on offering it to others as a managed service.
SET page:title "Home"INCR page:viewsA string, up to 512MB.HSET user:1 name AnnA hash.LPUSH feed post:9A list.SADD tags redisA set.SETBIT active 42 1BITCOUNT activeA bitmap.PFADD visitors u1PFCOUNT visitorsHyperLogLog. The count is an estimate, with a 0.81% standard error.GEOSEARCH shops FROMLONLAT 13.4 38.1 BYRADIUS 5 kmA geospatial index.TrapGEOADD takes longitude first, then latitude. Swap them and every distance is wrong.
Asked in interviews
AskedWhat are the different data types supported by Redis?ZRANGE board 0 9 REV WITHSCORESZINCRBY board 50 anaZREVRANK board anaZRANK counts from the lowest score. Both count from 0.OBJECT ENCODING boardSmall ones as a listpack. Large ones as a skip list plus a hash table.TipThe hash table answers ZSCORE in O(1). The skip list makes inserts and ranks O(log N).
TrapMembers with equal scores sort byte by byte, and REV reverses that order too.
Asked in interviews
AskedHow are Redis sorted sets implemented internally?SET session:42 data EX 3600EXPIRE cart:42 600TTL cart:42PERSIST cart:42TTL returns -1 for no TTL, and -2 for no key.HEXPIRE user:1 60 FIELDS 1 tokenTrapA plain SET clears the TTL. Add KEEPTTL to keep it. INCR and HSET keep it anyway.
Asked in interviews
AskedHow does key expiration work in Redis?KEYS user:*It's O(N) in one call, so it blocks every client. Avoid it in production.SCAN 0 MATCH user:* COUNT 100Repeat with the cursor it returns until that is 0. It may return a key twice.HSCAN user:1 0SSCAN tags 0ZSCAN board 0DEL cart:42It frees the memory on the main thread, so a huge value blocks everyone.UNLINK big:hashRedis frees the memory in the background.FLUSHDBFLUSHALLTrapNothing undoes FLUSHALL. Only a backup, or an AOF copy cut back to before it, brings the data back.
CONFIG SET maxmemory 2gbAt the cap, the default noeviction rejects writes. Reads still work.maxmemory-policy allkeys-lruallkeys-lfu evicts the least frequently used instead.maxmemory-policy volatile-lruUse it when cache keys share Redis with permanent ones.TipLRU and LFU are approximate. Redis samples 5 keys and evicts the best one.
TrapRedis may not return freed memory to the operating system. Size the server for peak use.
MEMORY USAGE user:1HSET user:1 name Ann age 30Every key costs extra memory, and Redis stores small hashes compactly.hash-max-listpack-entries 512The compact encoding is a listpack. Higher limits save memory but slow lookups.TrapA temporary key with no TTL stays in memory until eviction removes it.
Asked in interviews
AskedDescribe advanced Redis memory optimization techniques.redis-cli --bigkeysredis-cli --memkeysBoth scan, so they don't block.redis-cli --hotkeysIt needs an LFU eviction policy.TrapExpiring or evicting a big key blocks too, unless lazyfree-lazy-expire and lazyfree-lazy-eviction are on.
Asked in interviews
AskedWhat problems do big keys and hot keys cause, and how do you fix them?save 900 1RDB. A crash loses every write since the last snapshot.BGSAVEA forked child writes it. SAVE blocks every client instead.appendonly yesappendfsync everysecAOF. A crash loses about one second of writes.appendfsync alwaysEvery write waits for the disk.CONFIG SET save ""CONFIG SET appendonly noAfter a restart, Redis is empty.redis-cli --rdb /backup/dump.rdb Copying a running server's RDB file is safe too.TipWith both on, Redis loads the AOF at startup, because it's more complete.
TrapDon't let a master with persistence off restart by itself. It comes back empty, and its replicas copy the empty data.
MULTIEXECRedis queues them, then runs them in order with nothing in between.WATCH balanceOptimistic locking. EXEC returns null if it changed, so retry.MULTI adds isolation, and Lua adds logic.TipA command can't use an earlier one's result. Use a Lua script for that.
TrapThere is no rollback. Commands that succeeded stay applied when another one fails.
EVAL "return redis.call('GET', KEYS[1])" 1 kPass key names in KEYS, so it works in Redis Cluster.SCRIPT LOAD "<script>"EVALSHA <sha1> 1 kA restart clears the cache. Reload the script after a NOSCRIPT error.FCALL myfn 1 kFunctions came in 7.0 to replace EVAL. Redis saves them with the data.TrapA running script blocks every client. Keep scripts short.
Asked in interviews
AskedExplain Lua scripting in Redis and its advantages.SUBSCRIBE news sportsPSUBSCRIBE news:*PUBLISH news "hello"It returns how many subscribers got it.SSUBSCRIBE ordersSPUBLISH orders hiIn a cluster, plain PUBLISH goes to every node.TrapDelivery is at most once. An offline or crashed subscriber misses those messages for good.
LPUSH jobs job:1BRPOP jobs 0If the worker crashes, the job is lost.BLMOVE jobs doing RIGHT LEFT 0It moves the job to a processing list. Remove it with LREM when done.ZADD tasks 10 urgent:1BZPOPMAX tasks 0A sorted set scored by priority.TipA reliable queue can run a job twice. Make handlers idempotent, so a second run has the same result.
Asked in interviews
AskedHow do you implement Redis as a message queue?XADD orders * id 7 total 99The ID is a millisecond time plus a sequence number.XRANGE orders - +XGROUP CREATE orders g1 0 MKSTREAMWith $ instead of 0, it reads only new entries.XREADGROUP GROUP g1 w1 STREAMS orders >XACK orders g1 <id>Each entry goes to one worker and stays pending until acknowledged.XAUTOCLAIM orders g1 w2 60000 0Here it claims entries idle for 60 seconds or more.TipEntries stay in memory until you trim them with XTRIM or MAXLEN.
TrapRecovery isn't automatic. Pending entries wait until their worker rereads them or another worker claims them.
Asked in interviews
AskedExplain Redis Stream data structure and its use cases.REPLICAOF 10.0.0.1 6379It deletes this server's data and copies the master's.REPLICAOF NO ONEThen point the other replicas at it.PSYNC sends only what it missed. Otherwise the master sends a full snapshot.min-replicas-to-write 1min-replicas-max-lag 10It limits what a network split can lose.TrapReplication is asynchronous. A master can acknowledge a write and fail before any replica has it. WAIT narrows that window.
Asked in interviews
AskedHow does Redis replication work?sentinel monitor mymaster 10.0.0.1 6379 2The quorum is how many Sentinels must agree the master is down.SENTINEL get-master-addr-by-name mymasterClients must ask, unless a script moves a virtual IP to the new master.SENTINEL FAILOVER mymasterTrapThe quorum only marks the master down. A failover needs a majority of all Sentinels, so run at least three.
CLUSTER KEYSLOT user:42The slot is CRC16 of the key, mod 16,384. Each master owns a range of slots.MGET {user:42}:cart {user:42}:ordersA hash tag. Redis hashes only the part in braces.MOVED means the slot lives on another node now. ASK redirects one request mid-move.redis-cli --cluster reshard 10.0.0.1:6379Redis never reshards by itself. Moving a big key blocks both nodes.CLUSTER FAILOVERRun it on the replica. It waits until it has caught up.TrapMulti-key commands, transactions and scripts need all their keys in one slot. Otherwise they fail with CROSSSLOT.
Asked in interviews
AskedExplain Redis Cluster and its benefits.TipAdd random jitter to TTLs, so many keys don't expire together.
TrapWithout a TTL, a key whose invalidation goes missing stays stale forever. Put a TTL on every cached key.
DEL user:42Delete it rather than update it.CLIENT TRACKING ONClient-side caching. Redis sends an invalidation for each key the client read.TrapDelete after the database commit, never before. An earlier delete lets a reader cache the old value again.
SET lock:order:7 <token> NX PX 30000NX sets it only if it's free. The token is a random value unique to you.DELEX lock:order:7 IFEQ <token>Before 8.4, compare and delete in one Lua script.TrapA replica doesn't make a lock safe. The master can fail before the key reaches it, and a second client gets the same lock.
Asked in interviews
AskedHow would you implement distributed locking using Redis?With a limit of 3 a minute, the fixed window lets 6 requests through in 50 seconds. The sliding window rejects the last 3, drawn hollow.
INCR rl:42:1405EXPIRE rl:42:1405 60Fixed window. Set the expiry when INCR returns 1.TrapSeparate INCR and EXPIRE calls aren't atomic. A crash between them leaves a counter that never expires.
Asked in interviews
AskedDesign a Redis-based rate limiting system.ZADD idx:age 30 user:123ZRANGE idx:age 25 35 BYSCOREA sorted set scored by age is an index you keep by hand.SINTER friends:1 friends:2TrapA hand-made index drifts when a write path forgets it. Update the data and the index in one MULTI or script.
SLOWLOG GET 10slowlog-log-slower-than 10000The unit is microseconds.latency-monitor-threshold 100LATENCY LATESTThe latency monitor is off until you set this. The unit is milliseconds.INFO statsINFO memoryThe hit rate comes from keyspace_hits and keyspace_misses.MONITORIt can halve throughput, so run it only briefly.TrapDisable transparent huge pages on Linux. They slow the fork behind every RDB save and AOF rewrite.
Asked in interviews
AskedHow do you monitor and debug Redis performance issues?bind 127.0.0.1 10.0.0.5With no password and no bind, protected mode refuses remote clients.requirepass <password>ACL SETUSER app on >pw ~cache:* +@read -@dangeroustls-port 6380port 0port 0 closes the plain-text port.TipBlock FLUSHALL and CONFIG with -@dangerous, not the deprecated rename-command.
TrapA new ACL user starts disabled. Without on in its rule, every login fails.
Asked in interviews
AskedExplain Redis security best practices and implementation.Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in