Redis Mini Project
In this project you'll design the Redis side of a link shortener with analytics, like the services that turn a long URL into tad.link/3D7. It is a good Redis project because it uses almost every data type for what it does best:
| Feature | Redis structure |
|---|---|
| Unique short codes | string counter (INCR) + base-62 encoding |
| Link data | hash per link |
| Custom aliases without collisions | HSETNX / SET NX |
| Click counters per day | HINCRBY on a daily hash |
| Unique visitors | HyperLogLog |
| Most popular links | sorted set |
| Abuse protection | fixed-window rate limiter |
| Analytics pipeline | stream + consumer group |
| Atomic link creation | Lua script |
Each step is a runnable transcript. A real service would send these commands from application code (the last step shows how), but every command is exactly what the application would send.
Step 1: Short codes from a counter
Every new link gets the next number from a counter, and the number is written in base 62 (0-9, a-z, A-Z) to keep it short. INCR guarantees that two servers creating links at the same moment never get the same number. Starting the counter at a larger value avoids one-character codes:
SET next:link:id 13956
INCR next:link:id
INCR next:link:id
INCR next:link:idredis> SET next:link:id 13956
OK
redis> INCR next:link:id
(integer) 13957
redis> INCR next:link:id
(integer) 13958
redis> INCR next:link:id
(integer) 13959
The encoding itself happens in the application:
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base62(n):
if n == 0:
return ALPHABET[0]
digits = []
while n:
n, rem = divmod(n, 62)
digits.append(ALPHABET[rem])
return "".join(reversed(digits))
def from_base62(code):
n = 0
for ch in code:
n = n * 62 + ALPHABET.index(ch)
return n
for n in [13957, 13958, 13959, 1_000_000, 56_800_235_583]:
code = to_base62(n)
print(f"{n:>12} -> {code:<7} -> {from_base62(code)}") 13957 -> 3D7 -> 13957
13958 -> 3D8 -> 13958
13959 -> 3D9 -> 13959
1000000 -> 4c92 -> 1000000
56800235583 -> ZZZZZZ -> 56800235583
Three characters cover the IDs up to 238,327, and six characters cover more than 56 billion.
Step 2: Store the link
Each link is a hash keyed by its code. HSETNX on the url field means a code can never be silently overwritten. A second key maps each user to the list of their links, newest first:
HSETNX link:3D7 url "https://example.com/articles/learning-redis-in-30-days"
HSET link:3D7 owner user:7 created 1760700000 clicks 0
HSETNX link:3D7 url "https://evil.example/phishing"
HGET link:3D7 url
LPUSH user:7:links 3D7
LRANGE user:7:links 0 -1redis> HSETNX link:3D7 url "https://example.com/articles/learning-redis-in-30-days"
(integer) 1
redis> HSET link:3D7 owner user:7 created 1760700000 clicks 0
(integer) 3
redis> HSETNX link:3D7 url "https://evil.example/phishing"
(integer) 0
redis> HGET link:3D7 url
"https://example.com/articles/learning-redis-in-30-days"
redis> LPUSH user:7:links 3D7
(integer) 1
redis> LRANGE user:7:links 0 -1
1) "3D7"
Step 3: Custom aliases
Users may pick their own alias (tad.link/sale). Two users asking for the same alias at the same time must not both win: HSETNX decides atomically.
HSETNX link:sale url "https://shop.example/autumn-sale"
HSETNX link:sale url "https://other.example/sale"
HGET link:sale url
EXISTS link:free-giftredis> HSETNX link:sale url "https://shop.example/autumn-sale"
(integer) 1
redis> HSETNX link:sale url "https://other.example/sale"
(integer) 0
redis> HGET link:sale url
"https://shop.example/autumn-sale"
redis> EXISTS link:free-gift
(integer) 0
The second request got 0 and the application answers "alias already taken". EXISTS lets the form check availability while the user types.
Step 4: Redirect and count clicks
On each visit the application reads the URL and records the click. Several counters are updated in one transaction, so a report never sees half a click:
clicksin the link hash (total),- a field per day in
clicks:3D7:daily(for charts), - a HyperLogLog of visitor IDs per link (unique visitors),
- the global
top:linkssorted set (popularity).
HSET link:3D7 url "https://example.com/articles/learning-redis-in-30-days" clicks 0
HGET link:3D7 url
MULTI
HINCRBY link:3D7 clicks 1
HINCRBY clicks:3D7:daily 2026-10-17 1
PFADD uv:3D7 visitor:a1
ZINCRBY top:links 1 3D7
EXEC
MULTI
HINCRBY link:3D7 clicks 1
HINCRBY clicks:3D7:daily 2026-10-17 1
PFADD uv:3D7 visitor:a1
ZINCRBY top:links 1 3D7
EXEC
HGET link:3D7 clicks
PFCOUNT uv:3D7redis> HSET link:3D7 url "https://example.com/articles/learning-redis-in-30-days" clicks 0
(integer) 2
redis> HGET link:3D7 url
"https://example.com/articles/learning-redis-in-30-days"
redis> MULTI
OK
redis> HINCRBY link:3D7 clicks 1
QUEUED
redis> HINCRBY clicks:3D7:daily 2026-10-17 1
QUEUED
redis> PFADD uv:3D7 visitor:a1
QUEUED
redis> ZINCRBY top:links 1 3D7
QUEUED
redis> EXEC
1) (integer) 1
2) (integer) 1
3) (integer) 1
4) "1"
redis> MULTI
OK
redis> HINCRBY link:3D7 clicks 1
QUEUED
redis> HINCRBY clicks:3D7:daily 2026-10-17 1
QUEUED
redis> PFADD uv:3D7 visitor:a1
QUEUED
redis> ZINCRBY top:links 1 3D7
QUEUED
redis> EXEC
1) (integer) 2
2) (integer) 2
3) (integer) 0
4) "2"
redis> HGET link:3D7 clicks
"2"
redis> PFCOUNT uv:3D7
(integer) 1
The same visitor clicked twice: 2 clicks, but still 1 unique visitor.
Step 5: Popular links and reports
After a few more visits from different links, the dashboard needs the top links and a daily chart:
ZINCRBY top:links 42 3D7
ZINCRBY top:links 17 sale
ZINCRBY top:links 63 3D8
ZINCRBY top:links 5 3D9
ZRANGE top:links 0 2 REV WITHSCORES
HSET clicks:3D7:daily 2026-10-15 12 2026-10-16 18 2026-10-17 12
HMGET clicks:3D7:daily 2026-10-15 2026-10-16 2026-10-17
PFADD uv:3D7 visitor:a1 visitor:b2 visitor:c3
PFADD uv:3D8 visitor:c3 visitor:d4
PFCOUNT uv:3D7 uv:3D8redis> ZINCRBY top:links 42 3D7
"42"
redis> ZINCRBY top:links 17 sale
"17"
redis> ZINCRBY top:links 63 3D8
"63"
redis> ZINCRBY top:links 5 3D9
"5"
redis> ZRANGE top:links 0 2 REV WITHSCORES
1) "3D8"
2) "63"
3) "3D7"
4) "42"
5) "sale"
6) "17"
redis> HSET clicks:3D7:daily 2026-10-15 12 2026-10-16 18 2026-10-17 12
(integer) 3
redis> HMGET clicks:3D7:daily 2026-10-15 2026-10-16 2026-10-17
1) "12"
2) "18"
3) "12"
redis> PFADD uv:3D7 visitor:a1 visitor:b2 visitor:c3
(integer) 1
redis> PFADD uv:3D8 visitor:c3 visitor:d4
(integer) 1
redis> PFCOUNT uv:3D7 uv:3D8
(integer) 4
The last command estimates the unique visitors across both links: visitor c3 is counted only once.
Step 6: Rate-limit link creation
Spammers love link shorteners. Each user may create at most 3 links per minute, counted in a fixed window keyed by the minute number:
EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
TTL rl:create:user:7:29345000redis> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
(integer) 1
redis> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
(integer) 2
redis> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
(integer) 3
redis> EVAL "local n = redis.call('INCR', KEYS[1]) if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end return n" 1 rl:create:user:7:29345000
(integer) 4
redis> TTL rl:create:user:7:29345000
(integer) 60
The fourth attempt returned 4, more than the limit, so the application responds with HTTP 429.
Step 7: An analytics stream
Detailed analytics (country, browser, referrer) are too slow to compute during the redirect. Instead, the redirect appends an event to a stream and returns immediately; a worker in a consumer group processes the events later. The stream is capped so it can't grow without limit:
XADD events:clicks MAXLEN ~ 100000 1-1 code 3D7 country VN ref news.example
XADD events:clicks MAXLEN ~ 100000 2-1 code sale country FR ref mail
XADD events:clicks MAXLEN ~ 100000 3-1 code 3D7 country VN ref social.example
XGROUP CREATE events:clicks geo-stats 0
XREADGROUP GROUP geo-stats worker-1 COUNT 2 STREAMS events:clicks >
HINCRBY geo:3D7 VN 1
HINCRBY geo:sale FR 1
XACK events:clicks geo-stats 1-1 2-1
XPENDING events:clicks geo-statsredis> XADD events:clicks MAXLEN ~ 100000 1-1 code 3D7 country VN ref news.example
"1-1"
redis> XADD events:clicks MAXLEN ~ 100000 2-1 code sale country FR ref mail
"2-1"
redis> XADD events:clicks MAXLEN ~ 100000 3-1 code 3D7 country VN ref social.example
"3-1"
redis> XGROUP CREATE events:clicks geo-stats 0
OK
redis> XREADGROUP GROUP geo-stats worker-1 COUNT 2 STREAMS events:clicks >
1) 1) "events:clicks"
2) 1) 1) "1-1"
2) 1) "code"
2) "3D7"
3) "country"
4) "VN"
5) "ref"
6) "news.example"
2) 1) "2-1"
2) 1) "code"
2) "sale"
3) "country"
4) "FR"
5) "ref"
6) "mail"
redis> HINCRBY geo:3D7 VN 1
(integer) 1
redis> HINCRBY geo:sale FR 1
(integer) 1
redis> XACK events:clicks geo-stats 1-1 2-1
(integer) 2
redis> XPENDING events:clicks geo-stats
1) (integer) 0
2) (nil)
3) (nil)
4) (nil)
The worker processed two events, wrote country counters and acknowledged them. Event 3-1 has not been delivered yet, so nothing is pending; the next XREADGROUP call returns it.
Step 8: Create a link atomically with Lua
Creating a link touches several keys: the rate limiter, the link hash, the user's list. A script does it in one atomic step and returns a clear error when something is wrong:
-- KEYS: rate-limit key, link key, user's link list
-- ARGV: code, url, owner, created, limit
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('EXPIRE', KEYS[1], 60) end
if n > tonumber(ARGV[5]) then
return redis.error_reply('RATELIMIT too many links, try again later')
end
if redis.call('HSETNX', KEYS[2], 'url', ARGV[2]) == 0 then
return redis.error_reply('TAKEN alias already in use')
end
redis.call('HSET', KEYS[2], 'owner', ARGV[3], 'created', ARGV[4], 'clicks', 0)
redis.call('LPUSH', KEYS[3], ARGV[1])
return ARGV[1]Loaded as a function library, the application calls it by name:
FUNCTION LOAD "#!lua name=links\nredis.register_function('create_link', function(keys, args) local n = redis.call('INCR', keys[1]) if n == 1 then redis.call('EXPIRE', keys[1], 60) end if n > tonumber(args[5]) then return redis.error_reply('RATELIMIT too many links, try again later') end if redis.call('HSETNX', keys[2], 'url', args[2]) == 0 then return redis.error_reply('TAKEN alias already in use') end redis.call('HSET', keys[2], 'owner', args[3], 'created', args[4], 'clicks', 0) redis.call('LPUSH', keys[3], args[1]) return args[1] end)"
FCALL create_link 3 rl:create:user:9:29345000 link:sale user:9:links sale https://shop.example/sale user:9 1760700000 3
FCALL create_link 3 rl:create:user:9:29345000 link:sale user:9:links sale https://copy.example/sale user:9 1760700010 3
FCALL create_link 3 rl:create:user:9:29345000 link:tea user:9:links tea https://shop.example/teapots user:9 1760700020 3
FCALL create_link 3 rl:create:user:9:29345000 link:mug user:9:links mug https://shop.example/mugs user:9 1760700030 3
HGETALL link:sale
LRANGE user:9:links 0 -1redis> FUNCTION LOAD "#!lua name=links\nredis.register_function('create_link', function(keys, args) local n = redis.call('INCR', keys[1]) if n == 1 then redis.call('EXPIRE', keys[1], 60) end if n > tonumber(args[5]) then return redis.error_reply('RATELIMIT too many links, try again later') end if redis.call('HSETNX', keys[2], 'url', args[2]) == 0 then return redis.error_reply('TAKEN alias already in use') end redis.call('HSET', keys[2], 'owner', args[3], 'created', args[4], 'clicks', 0) redis.call('LPUSH', keys[3], args[1]) return args[1] end)"
"links"
redis> FCALL create_link 3 rl:create:user:9:29345000 link:sale user:9:links sale https://shop.example/sale user:9 1760700000 3
"sale"
redis> FCALL create_link 3 rl:create:user:9:29345000 link:sale user:9:links sale https://copy.example/sale user:9 1760700010 3
(error) TAKEN alias already in use
redis> FCALL create_link 3 rl:create:user:9:29345000 link:tea user:9:links tea https://shop.example/teapots user:9 1760700020 3
"tea"
redis> FCALL create_link 3 rl:create:user:9:29345000 link:mug user:9:links mug https://shop.example/mugs user:9 1760700030 3
(error) RATELIMIT too many links, try again later
redis> HGETALL link:sale
1) "url"
2) "https://shop.example/sale"
3) "owner"
4) "user:9"
5) "created"
6) "1760700000"
7) "clicks"
8) "0"
redis> LRANGE user:9:links 0 -1
1) "tea"
2) "sale"
Note that the failed TAKEN attempt still counted against the rate limit, which is usually what you want for an abuse limit.
Step 9: The application code
Finally, here is how a small Python web handler would use these keys with redis-py. The Redis commands are the ones you ran above:
import time
import redis
r = redis.Redis(decode_responses=True)
create_link = r.register_script(open("create_link.lua").read()) # the Step 8 script
def shorten(user_id, url, alias=None):
code = alias or to_base62(r.incr("next:link:id"))
window = int(time.time()) // 60
return create_link(
keys=[f"rl:create:user:{user_id}:{window}", f"link:{code}", f"user:{user_id}:links"],
args=[code, url, f"user:{user_id}", int(time.time()), 3],
)
def redirect(code, visitor_id):
url = r.hget(f"link:{code}", "url")
if url is None:
return 404, None
day = time.strftime("%Y-%m-%d")
with r.pipeline() as pipe: # MULTI/EXEC sent in one round trip
pipe.hincrby(f"link:{code}", "clicks", 1)
pipe.hincrby(f"clicks:{code}:daily", day, 1)
pipe.pfadd(f"uv:{code}", visitor_id)
pipe.zincrby("top:links", 1, code)
pipe.xadd("events:clicks", {"code": code, "visitor": visitor_id}, maxlen=100_000, approximate=True)
pipe.execute()
return 302, urlIdeas to extend the project
- Expiring links:
EXPIRE link:{code}for temporary links, andEXPIRETIMEto show when they end. - Cache the hot path: keep the 1,000 most popular URLs in an in-process cache and invalidate with pub/sub.
- Bitmaps for retention: one bitmap per day of user IDs that created a link, then
BITOP ANDto find users active on both days. - Search: index link titles with the Query Engine (
FT.CREATE ... PREFIX 1 link:). - Security: run the service as an ACL user limited to
~link:* ~clicks:* ~uv:* ~top:* ~rl:* ~events:* ~user:* ~next:*without@dangerouscommands.
Test yourself
Why does the shortener use INCR to generate link IDs?
- It is the only command that returns numbers
- It returns a unique, increasing number even when many servers call it at once
- It encodes base 62
- It sets an expiry
Which structure counts unique visitors per link in constant memory?
- A set per link
- A HyperLogLog per link
- A list per link
- The top:links sorted set
Why does the redirect append to a stream instead of computing detailed analytics itself?
- Streams are required for redirects
- So the redirect stays fast; a consumer group processes events later and reliably
- Because hashes cannot store countries
- To delete old links