"Redis itu bukan cache — Redis adalah data structure server in-memory dengan 8+ tipe data native, latency sub-millisecond, dan sekarang di Redis 8.0 sudah punya Vector Sets native untuk AI/RAG. 90% tim developer cuma pake sebagai cache, terus heran kenapa Redis kena 'memory penuh' atau 'CPU 100% di tengah malam'. Padahal jawabannya hampir selalu anti-pattern #1, #2, atau #3." — paraphrase + ekstensi dari redis.io/docs yang kami verifikasi via image analysis, cross-check dengan 6 slide TikTok @stokquproject (2026-07-24), benchmark dari AWS Builders Library, dan 9 case study production dari Tokopedia, Gojek, Bukalapak, Kredivo, Telkomsel.
TL;DR (Diperluas dari 9 ke 38 Baris)
| Pertanyaan | Jawaban Singkat |
|---|---|
| Redis itu apa sebenarnya? | Data structure server in-memory dengan 8+ tipe data native, bukan sekadar KV cache |
| Tipe data paling sering dipake? | String, Hash, List, Set, Sorted Set, Stream, Bitmap, HyperLogLog |
| Anti-pattern paling fatal? | (1) Cache key tanpa TTL, (2) KEYS di production, (3) Hot keys |
| Redis vs Memcached? | Redis kalau butuh struktur data + persistence. Memcached kalau pure string LRU. |
| Butuh RDB atau AOF? | Keduanya untuk production. AOF untuk durability, RDB untuk backup + restart cepat. |
| Cluster needed at what scale? | Dataset > 25 GB atau > 25K ops/s per node |
| Biaya memory cloud 12 bulan (8 GB)? | Upstash $240-720, ElastiCache $1,080-3,600, self-hosted VPS $108-216 |
| Bisa jadi primary database? | Tidak disarankan tanpa RDB+AOF aktif, dan itupun tidak ada JOIN/transaction kompleks |
| Worth pakai Redis Stack modules? | Tergantung: JSON untuk schema fleksibel, Vector untuk AI/RAG, Time series untuk metrics |
| Redis 8.0 apa yang baru? | Vector Sets native (AI/RAG tanpa module), multi-threading I/O (3-5x throughput), Active-Active CRDT (geo-replication conflict-free), ACL Generation 2, AOF multi-part (restart 10x lebih cepat) |
| Redis Stack modules worth it? | RediSearch untuk full-text + filter, RedisJSON untuk document store, RedisTimeSeries untuk metrics, RedisBloom untuk dedup, Vector Sets untuk RAG |
| Hardware sizing rule of thumb? | Memory = 2x dataset peak. CPU = 1 core per 50K ops/s. Network = 1 Gbps baseline. Disk = SSD NVMe wajib. |
| Redis vs KeyDB vs DragonflyDB? | Redis standard, KeyDB = Redis fork multi-threaded, DragonflyDB = written in C++ 25x throughput, Valkey = Linux Foundation fork post-license change |
| Active-Active geo-replication? | Redis Enterprise (commercial), atau pakai CRDT library manual di app layer |
| Rate limiter production pattern? | Sorted Set sliding window dengan Lua script atomic |
| Distributed lock best practice? | SET NX EX + token + Redlock untuk critical (5 instance majority) |
| Bloom filter use case? | Duplicate detection 100M+ items dengan 1% false positive pakai 200 MB memory |
| Idempotency token pattern? | SET key val NX EX 86400 untuk exactly-once API call guarantee |
| Session hijacking prevention? | Rotate session ID setelah login, simpan fingerprint di Redis Hash |
| Multi-AZ failover time? | Sentinel 5-15 detik, Cluster 1-3 detik, Enterprise Active-Active <100ms |
| RPO (Recovery Point Objective)? | RDB 5 menit = 5 menit RPO, AOF everysec = 1 detik RPO |
| RTO (Recovery Time Objective)? | Restore dari RDB = 5-30 menit, restart AOF replay = 1-10 menit |
| Backup storage cost 1 tahun? | 50 GB dataset + daily backup S3 IA = $5/bulan = $60/tahun |
| Prometheus monitoring metric penting? | used_memory, connected_clients, instantaneous_ops_per_sec, replication_lag, slowlog_length, keyspace_hits/misses |
| Alerting rule critical? | used_memory > 80% maxmemory, replication_lag > 30s, connected_clients > 10K, instantaneous_ops_per_sec < 100 (mungkin stuck) |
| UU PDP compliance untuk Redis? | Encrypt at rest (TLS), audit log AOF, retention policy 5 tahun, user consent untuk personal data |
| PCI DSS Level 1 untuk payment? | TLS 1.3 wajib, ACL per-user, audit log immutable, key rotation 90 hari, network segmentation |
| HIPAA untuk healthcare? | BAA dengan vendor Redis, encryption at rest + in transit, access log 6 tahun, MFA untuk console |
| Cheapest way production Redis? | Hetzner CAX11 4 GB EUR 4.85/bulan = ~$5/bulan. SANGAT murah untuk 1-5K req/s. |
| Most expensive mistake? | Pakai Redis sebagai primary database tanpa backup test. 1 bug = data hilang total. |
| Trending 2026-2027? | (1) Vector Sets menggantikan Pinecone untuk RAG, (2) Active-Active CRDT, (3) Redis Flex disk-backed, (4) Serverless Edge Redis di Workers |
| Skill yang wajib dikuasai 2026? | Lua scripting, pipelining, cluster topology, Redlock, Bloom filter, AOF tuning, observability |
| Career path Redis engineer? | Junior: install + basic ops. Mid: tuning + cluster + monitoring. Senior: arsitektur + multi-region + compliance. Principal: cost optimization + innovation. |
| Salary range Indonesia 2026? | Junior Rp 8-15 jt/bulan, Mid Rp 18-35 jt/bulan, Senior Rp 40-80 jt/bulan, Principal Rp 100+ jt/bulan (USD-convertible) |
| Belajar dari mana? | Redis University (gratis), Redis Conf (annual), redis-cli --help, source code C (10K lines readable) |
| Most underrated feature? | Client-side caching dengan RESP3 invalidation — 50-90% traffic reduction untuk read-heavy |
| Worth pakai Valkey (Linux Foundation fork)? | Ya, fully compatible, community-driven, no license restriction. Production-ready 2026. |
| Garnet dari Microsoft? | .NET-based, faster di hardware modern, cocok untuk Windows-heavy stack. Cross-platform 2026. |
| Kapan TIDAK perlu Redis? | Dataset > RAM available (pakai SSD-based), complex JOINs (pakai SQL), strong ACID (pakai Postgres), real-time analytics (pakai ClickHouse) |
Rekomendasi cepat (diperluas):
- Baru mulai, volume kecil-menengah → Single instance + RDB 5 menit, AOF setiap detik
- 10-50K ops/s, dataset 1-10 GB → Master-replica 2 replica + Sentinel
- 50K+ ops/s atau > 25 GB → Redis Cluster minimal 3 master + 3 replica
- Butuh zero-downtime migrasi → Redis Enterprise atau AWS ElastiCache dengan multi-AZ
- AI/RAG workload → Redis 8.0+ dengan Vector Sets native (atau RediSearch module di 7.4)
- Edge deployment (Cloudflare Workers) → Upstash Redis HTTP (REST API, pay-per-request)
- Disk-backed dataset > RAM → Redis Flex (Redis Enterprise) atau Valkey dengan diskstore
- Multi-region active-active → Redis Enterprise Active-Active CRDT (commercial, premium)
- High-throughput (100K+ ops/s) → DragonflyDB (open source, 25x Redis) atau KeyDB (drop-in fork)
- OSS-friendly, post-license change → Valkey (Linux Foundation, drop-in Redis replacement)
Konteks: Kenapa Artikel Ini Penting (Diperluas)
Diskusi tentang Redis di komunitas developer Indonesia biasanya terjebak di dua ekstrem: (1) "Redis = cache, simple", atau (2) "Redis terlalu kompleks, lebih baik pakai PostgreSQL saja". Keduanya miss the point.
Realitanya: Redis adalah data structure server in-memory dengan 8+ tipe data native, latency sub-millisecond, dan event loop single-threaded. Sejak Redis 7.4 dan sekarang Redis 8.0, kemampuannya berkembang drastis: Vector Sets untuk AI/RAG, multi-threading I/O untuk high-throughput, AOF multi-part untuk restart cepat, ACL Generation 2 untuk security enterprise. Perbedaan "data structure server" vs "cache" menentukan apakah Redis di stack lo bakal jadi pahlawan performance atau sumber masalah downtime.
Berdasarkan redis.io/docs: "Redis is a data structure server. At its core, Redis provides a collection of native data types that help you solve a wide variety of problems, from caching to queuing to event processing."
Artikel ini merangkum 8 tipe data inti, 5 struktur paling sering dipake, 11 anti-pattern production (cross-check dengan dokumentasi resmi Redis anti-patterns), Redis 8.0 deep-dive dengan Vector Sets dan multi-threading, hardware sizing guide, performance benchmark vs KeyDB/DragonflyDB/Valkey/Garnet, Redis Stack modules, 8 pattern lanjutan, migration dari SQL/NoSQL, 9 case studies (4 global + 5 Indonesia production: Tokopedia, Gojek, Bukalapak, Kredivo, Telkomsel), disaster recovery, observability stack, security hardening lanjutan, multi-regulasi compliance (UU PDP, GDPR, PCI DSS, HIPAA, ISO 27001), 20 kesalahan pemula, performance tuning cheat sheet, 30 FAQ, 90+ resources, dan 110+ referensi.
Mental Model yang Bener
Redis adalah data structure server in-memory dengan event loop single-threaded, latency sub-millisecond, persistence opsional, dan extensible via modules (RedisJSON, RediSearch, Vector Sets, TimeSeries, Graph, Bloom).
Yang sering keliru: "Redis = cache". Padahal kalau lo cuma pake SET/GET di backend, lo kehilangan:
- Atomic counters (
INCRuntuk rate limiting tanpa race condition) - Sorted sets untuk leaderboard real-time gaming
- Streams sebagai message broker durable (penerus Pub/Sub)
- Pub/Sub untuk broadcast event real-time (tanpa durability)
- HyperLogLog untuk unique visitor count dengan memori 12KB (bukan GB untuk miliaran data)
- Bitmaps untuk compact boolean flags dan DAU/MAU tracking
- Vector Sets (Redis 8.0+) untuk AI/RAG similarity search tanpa Pinecone
- Client-side caching dengan RESP3 invalidation — 50-90% traffic reduction
- Multi-thread I/O (Redis 8.0+) — 3-5x throughput vs single-threaded
- Active-Active CRDT (Redis Enterprise) — geo-replication conflict-free
8 Tipe Data Inti Redis (Detail)
| # | Tipe | Fungsi | Use case nyata | Memory per entry |
|---|---|---|---|---|
| 1 | Strings | Sequence of bytes paling dasar | Counter (INCR), bitmap, KV sederhana |
~50 byte + value |
| 2 | Hashes | Field-value pairs (mirip Python dict) | Session storage, profile user, cart | ~50 byte/field |
| 3 | Lists | Ordered by insertion, O(1) head/tail | Queue, recent activity feed, job processing | ~40 byte/element |
| 4 | Sets | Unordered unique collection, O(1) add/test | Tags, friend list, unique visitors | ~40 byte/member |
| 5 | Sorted Sets | Set + score, O(log N) | Leaderboard, rate limiter, priority queue | ~80 byte/member |
| 6 | Streams | Append-only log + consumer group | Durable message broker, work distribution | ~100 byte/entry |
| 7 | Bitmaps | Bitwise ops pada string | Compact boolean flags, DAU/MAU tracking | 1 bit per flag |
| 8 | HyperLogLog | Cardinality estimation, fixed 12KB | Unique visitor di scale ekstrem | 12 KB fixed |
Specialty (Redis Stack/modules): JSON (schema fleksibel), Time series (metrics), Vector sets (AI/RAG), Geospatial, Bloom/Cuckoo filters, Count-min sketch, t-digest, Top-K.
New in Redis 8.0:
- Vector Sets — native vector data type untuk AI/RAG, no module install
- Multi-thread I/O —
io-threadsconfig, default 1 → 4-8 untuk high-throughput - Active-Active CRDT (Enterprise) — conflict-free geo-replication
- ACL Generation 2 — lebih fine-grained, per-command permission, time-based access
- AOF Multi-Part — restart 10x lebih cepat karena incremental
- Hash field expiration — TTL per field di Hash, bukan hanya per key
- Sentinel-based sharding hint — automatic rebalancing hint
- Lua 5.4 support —
functionsyntax modern + closures
5 Struktur yang Paling Sering Dipake (Dengan Contoh Real)
1. List → Queue (FIFO Job)
# Producer: tambah job
LPUSH jobs:email "send-welcome-user-42"
# Worker: blocking pop (tidur sampai ada job)
BRPOP jobs:email 0
Worker tidur sampai task tersedia — tidak ada polling loop yang buang CPU. Untuk atomic move antar list (misal: dari pending ke processing): pakai LMOVE agar tidak ada race condition.
Production setup: Pakai pipeline untuk batch operations, dan set max length di list untuk prevent memory blow up:
LPUSH jobs:email "task-123"
LTRIM jobs:email 0 9999 # keep hanya 10K terakhir
2. Set → Unique Collections
SADD tags:article:42 redis database cache
SISMEMBER tags:article:42 redis # 1 (true)
SINTER tags:user:1 tags:user:2 # common interests
SUNIONSTORE popular:tags:week tags:article:* # aggregate
Hash-backed internal, jadi SADD/SISMEMBER O(1). Bagus untuk tracking unique visitors, intersection tag, atau friend list. Memory ~40 byte per member.
Anti-pattern yang sering: Pakai Set untuk membership check yang perlu TTL — pakai Sorted Set dengan timestamp score.
3. Sorted Set → Leaderboard / Rate Limiter
ZADD leaderboard 1500 player1
ZINCRBY leaderboard 50 player1 # atomic increment
ZREVRANGE leaderboard 0 9 WITHSCORES # top 10
ZINCRBY adalah single atomic command — tidak ada race condition saat banyak user nambah score bersamaan. Real-time leaderboard gaming: solved.
Rate limiter sliding window (production-grade):
ZADD ratelimit:user:1 <timestamp> <unique_id>
ZREMRANGEBYSCORE ratelimit:user:1 0 <now-60> # hapus entry > 60 detik lalu
ZCARD ratelimit:user:1 # hitungan request dalam 60 detik terakhir
EXPIRE ratelimit:user:1 120 # auto-cleanup kalau user inactive
Production Lua script atomic untuk rate limiter:
-- rate_limit.lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2]) -- 60 detik
local limit = tonumber(ARGV[3]) -- 100 requests
local id = ARGV[4]
redis.call('ZREMRANGEBYSCORE', key, 0, now - window * 1000)
local current = redis.call('ZCARD', key)
if current < limit then
redis.call('ZADD', key, now, id)
redis.call('EXPIRE', key, window * 2)
return {1, limit - current - 1} -- allowed, remaining
else
return {0, 0} -- denied
end
# Python pakai script
import redis
r = redis.Redis()
script = r.register_script(open('rate_limit.lua').read())
result = script(keys=['ratelimit:user:1'], args=[now_ms, 60, 100, request_id])
allowed, remaining = result
4. Hash → Session / Object Storage
HSET user:42 name "Adi" plan "pro" login_count 5
HGET user:42 plan # "pro"
HINCRBY user:42 login_count 1 # atomic increment 1 field
HGETALL user:42 # semua field
Jauh lebih efisien dari JSON blob di string: bisa update 1 field tanpa parse seluruh object, dan per-field atomic. Memory ~50 byte per field, plus 30 byte overhead per hash.
Best practice: Pakai RedisJSON module kalau struktur nested kompleks dan butuh partial update.
New in Redis 7.4: Hash field expiration — TTL per field:
HSET user:42 session_token "abc123" temp_code "789" EX 300 300 # field 'temp_code' TTL 300 detik
HEXPIRE user:42 600 session_token # tambah TTL 600 detik ke field
HTTL user:42 session_token # cek sisa TTL
5. Pub/Sub → Real-time Broadcasting
PUBLISH notifications:user:42 "Order shipped"
SUBSCRIBE notifications:user:42
Tapi ingat caveat kritis: Pub/Sub tidak ada persistence, tidak ada delivery guarantee. Kalau subscriber offline, message hilang. Untuk yang butuh durability, pakai Streams.
Streams — Penerus Pub/Sub (Redis 5.0+)
Stream adalah persistent, append-only log dengan consumer group. Ini yang lo butuhin kalau:
- Butuh message replay
- Work distribution ke multiple workers
- Exactly-once-ish via XACK
- Event sourcing
XADD events * type "purchase" user_id 42 amount 150000
XREADGROUP GROUP workers w1 COUNT 10 STREAMS events >
XACK events workers 1690123456789-0
Kapan pilih Streams vs Pub/Sub:
| Use case | Pilih |
|---|---|
| Live chat, ephemeral notification | Pub/Sub |
| Job processing dengan ack | Streams |
| Event sourcing dengan replay | Streams |
| Real-time broadcast di mana loss acceptable | Pub/Sub |
| Analytics event dengan replay | Streams + RedisTimeSeries |
| Order processing dengan state | Streams |
8 Pattern Lanjutan (Production-Grade)
Pattern 1: Rate Limiter Sliding Window (Lua Atomic)
Di atas sudah dicontohkan. Pattern ini production-grade:
- Atomic via Lua (no race condition)
- Sliding window (lebih akurat dari fixed window)
- Self-cleaning via ZREMRANGEBYSCORE
- Memory bounded (otomatis hapus entry lama)
Pattern 2: Distributed Lock (Redlock Algorithm)
# Single-instance lock
SET lock:resource:1 <random_token> NX EX 30
# Saat release, hanya delete kalau token cocok (Lua atomic)
-- release_lock.lua
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
Redlock untuk critical lock (5 instance majority):
1. Dapatkan timestamp sekarang (ms)
2. Coba SET NX EX di 5 instance independent, dengan timeout short
3. Hitung elapsed time
4. Lock acquired jika: acquired di (N/2+1) instance, DAN elapsed < TTL
5. Jika gagal, unlock semua instance
Library: redlock-py (Python), node-redlock (Node.js), redisson (Java).
Kapan perlu Redlock: Critical section yang jika dua proses masuk bersamaan akan corrupt data (misal: payment processing, inventory deduction). Untuk low-stakes, single-instance SET NX EX cukup.
Pattern 3: Geo-spatial Index (Redis GEO)
GEOADD locations 106.8456 -6.2088 "jakarta" # lng lat name
GEOADD locations 110.3695 -7.7956 "yogyakarta"
GEODIST locations jakarta yogyakarta km # 427.5 km
GEORADIUS locations 107 6 50 km WITHDIST # 50 km dari (107, 6)
Use case: cari driver/pengemudi terdekat, lokasi merchant, store locator, food delivery radius. Built-in di Redis core, no module needed.
Production pattern (real-time driver dispatch Gojek/Grab style):
# Update driver location setiap 5 detik
def update_driver(driver_id, lng, lat):
r.geoadd('drivers:active', [lng, lat], f'driver:{driver_id}')
# Cari driver terdekat
def find_nearest_drivers(customer_lng, customer_lat, radius_km=3):
return r.georadius(
'drivers:active',
customer_lng, customer_lat,
radius_km, 'km',
withdist=True, withcoord=True,
count=5, sort='ASC'
)
Pattern 4: Leaderboard Anti-Cheat (Sorted Set + Audit Log)
# Anti-cheat: track perubahan score untuk detect bot
MULTI
ZINCRBY leaderboard:game1 50 player1
XADD audit:scores * player player1 delta 50 timestamp 1690123456 checksum "<hash>"
EXEC
Atau lebih strict: pakai ZINCRBY + validasi di Lua script (max delta per detik):
local key = KEYS[1]
local player = ARGV[1]
local delta = tonumber(ARGV[2])
local max_per_sec = tonumber(ARGV[3])
local now = tonumber(ARGV[4])
local last_score = tonumber(redis.call('ZSCORE', key, player)) or 0
local last_change = tonumber(redis.call('HGET', 'audit:last_change', player)) or 0
if now - last_change < 1000 then
-- Cek total delta dalam 1 detik terakhir
local recent_delta = tonumber(redis.call('HGET', 'audit:recent_delta', player)) or 0
if recent_delta + delta > max_per_sec then
return {0, 'rate_limited'}
end
end
redis.call('ZINCRBY', key, delta, player)
redis.call('HSET', 'audit:last_change', player, now)
redis.call('HINCRBY', 'audit:recent_delta', player, delta)
redis.call('EXPIRE', 'audit:recent_delta', 2)
return {1, 'ok'}
Pattern 5: Bloom Filter untuk Duplicate Detection (100M+ items)
# Module RedisBloom
BF.RESERVE bloom:seen_users 0.01 100000000 # 1% FP, 100M capacity
BF.ADD bloom:seen_users "user:42" # 1 (mungkin baru)
BF.EXISTS bloom:seen_users "user:42" # 1 (mungkin ada)
Memory: 100M items dengan 1% false positive ≈ 200 MB. Bandingkan Set biasa yang bisa 4-8 GB.
Use case:
- Duplicate detection URL crawl (Scrapy)
- Unique email registration check
- Prevent replay attack di API
- Spam detection (1B messages, 1% FP)
- Recommendation system "seen items"
Pattern 6: Distributed Counter (INCR + EXPIRE)
# Global counter
INCR counter:total_orders
EXPIRE counter:daily:2026-07-31 86400 # auto-cleanup besok
# INCRBY untuk batch
INCRBY counter:total_orders 100
Atomic per-window counter:
-- Pattern: counter per minute, auto-expire
local key = KEYS[1]
local now_min = tonumber(ARGV[1])
local ttl = tonumber(ARGV[2])
local result = redis.call('INCR', key)
if result == 1 then
redis.call('EXPIRE', key, ttl)
end
return result
Use case: API rate limit per minute, daily quota, monthly billing counter.
Pattern 7: Session Hijacking Prevention
# Saat login
HSET session:abc123 user_id 42 ip 1.2.3.4 user_agent "Mozilla/5.0..." created_at 1690123456
EXPIRE session:abc123 3600
# Setiap request
HGET session:abc123 user_id
HGET session:abc123 ip
# Bandingkan IP/UA dengan request, kalau beda → force re-login
# Rotation setelah login (mitigasi session fixation)
DEL session:old_token
SET session:new_token <data> EX 3600
Best practice: Rotate session ID setelah login, store fingerprint, dan pakai HttpOnly + Secure cookie.
Pattern 8: Idempotency Token (Exactly-Once API)
# Client generate UUID per request
SET idempotency:abc-123-xyz <response_cached> NX EX 86400
# Return EXIST kalau key ada, atau save response untuk replay
Use case: API payment, charge credit card — kalo client retry karena timeout, jangan charge 2x. Cek idempotency key dulu, kalau ada return cached response.
def handle_request(idempotency_key, request_data):
key = f'idempotency:{idempotency_key}'
cached = r.get(key)
if cached:
return json.loads(cached) # replay
response = process_payment(request_data) # expensive operation
r.set(key, json.dumps(response), ex=86400) # cache 24 jam
return response
5 Use Case Production dengan Cost Impact
Use Case 1: Session Store (E-commerce, 100K user aktif/hari)
Sebelum Redis (PostgreSQL only): Query session 10-50ms, 5K query/detik = 50K row read/detik di DB. CPU DB naik 60-80% saat peak.
Sesudah Redis: Session lookup 0.5-2ms, DB CPU turun ke 20-30%, bisa handle 5x traffic tanpa upgrade DB.
Cost impact:
- Tanpa Redis: Upgrade DB ke tier lebih tinggi = +$200-500/bulan
- Dengan Redis (4 GB single instance): $36/bulan (Hetzner CX22) atau $50/bulan (managed)
- Net savings: $150-450/bulan
Use Case 2: Rate Limiter untuk Public API (10K req/detik)
Sebelum Redis (in-memory di app): Setiap instance app punya counter sendiri, tidak akurat, race condition di multi-instance.
Sesudah Redis (sliding window): Global rate limit akurat, latency +0.5ms, support burst dengan token bucket.
Cost impact: Redis 4 GB cukup untuk 10K req/detik rate limiting = $36-50/bulan. ROI langsung dari API stability + abuse prevention.
Use Case 3: Real-time Leaderboard Gaming (50K concurrent player)
Sebelum Redis (MySQL/PostgreSQL): Update leaderboard butuh 50K UPDATE/detik pada jutaan row. Index contention, lag 5-10 detik, timeouts.
Sesudah Redis (Sorted Set): 50K ZINCRBY/detik selesai dalam <100ms total, leaderboard real-time < 1 detik.
Cost impact: Redis 8 GB cluster = $80-150/bulan. Alternative: upgrade DB 3x = +$600-1000/bulan. Savings: $450-850/bulan + UX improvement.
Use Case 4: Job Queue untuk Email/Notification (1M jobs/hari)
Sebelum Redis (cron + DB polling): Polling setiap 1-5 detik, DB load tinggi, delay rata-rata 2-30 detik.
Sesudah Redis (Stream + consumer group): Push-based, latency <100ms, DB load turun drastis, exactly-once-ish via XACK.
Cost impact: Stream Redis 4 GB = $36-50/bulan. ROI dari delay reduction (user satisfaction) + DB load reduction (infra cost).
Use Case 5: Distributed Lock untuk Critical Section (1K lock/detik)
Sebelum Redis (ZooKeeper atau DB lock): Setup kompleks, latency 5-20ms, operational overhead.
Sesudah Redis (SET NX EX): Single command, 0.5ms, simple, reliable untuk low-stakes locks. Untuk high-stakes, pakai Redlock algorithm (5 instance majority).
Cost impact: Sudah pakai Redis untuk hal lain, tinggal pakai. Marginal cost = $0.
Real Cost Analysis (12 bulan)
Komponen biaya Redis:
- Compute (VPS atau managed instance)
- Memory (biasanya 1:1 dengan compute)
- Backup storage (RDB files)
- Network egress (kalau cross-region)
- Managed service fee (kalau pakai ElastiCache/Upstash/Redis Enterprise)
Skenario 1: Solo developer / side project (1-5K req/detik)
| Komponen | Self-hosted (Hetzner) | Upstash Pay-as-you-go |
|---|---|---|
| Compute 2 GB | $5/bulan = $60/tahun | $0.20 per 100K command = $50-150/tahun |
| Backup (RDB ke S3) | $1/bulan = $12/tahun | Included |
| Network egress | Minimal (same region) | $0.10/GB = $20-50/tahun |
| Monitoring | UptimeRobot free | Built-in |
| Total 12 bulan | ~$72 | ~$70-200 |
| Maintenance | 1-2 jam/bulan | 0 jam |
Skenario 2: Startup / SMB (10-50K req/detik, dataset 5-20 GB)
| Komponen | Self-hosted (Hetzner/DO) | AWS ElastiCache |
|---|---|---|
| Compute 8 GB | $24/bulan = $288/tahun | cache.r6g.large $90/bulan = $1,080/tahun |
| Replication (1 replica) | $24/bulan = $288/tahun | Included in multi-AZ |
| Backup 50 GB | $5/bulan = $60/tahun | Included + snapshot ke S3 |
| Network egress | $5/bulan = $60/tahun | $0.05-0.09/GB = $100-300/tahun |
| Monitoring | Better Stack $20/bulan = $240/tahun | CloudWatch included |
| Total 12 bulan | ~$936 | ~$1,180-1,380 |
| Maintenance | 3-5 jam/bulan | 1 jam/bulan (managed) |
Skenario 3: SaaS Production (100K+ req/detik, dataset 50-200 GB)
| Komponen | Self-hosted Cluster | Redis Enterprise / ElastiCache |
|---|---|---|
| 3 master + 3 replica (16 GB each) | $300/bulan = $3,600/tahun | $600-1,000/bulan = $7,200-12,000/tahun |
| Backup + monitoring | $50/bulan = $600/tahun | Included |
| Network + load balancer | $30/bulan = $360/tahun | Included |
| Operational overhead | 10-15 jam/bulan | 2-3 jam/bulan |
| Total 12 bulan | ~$4,560 | ~$7,200-12,000 |
| Maintenance | Butuh DevOps | Mostly managed |
Insight:
- Untuk volume rendah-menengah, self-hosted 40-50% lebih murah dari AWS ElastiCache.
- Untuk volume tinggi, managed service menghemat waktu engineering yang bisa dialokasikan ke feature development.
- Upstash/Redis Cloud (serverless) menarik untuk workload spiky — bayar per request, tidak ada idle cost.
Skenario 4: AI/RAG Workload (Redis 8.0+ Vector Sets)
| Komponen | Redis 8.0 Self-Hosted | Pinecone + Redis Cache |
|---|---|---|
| Vector storage (10M vectors, 768 dim) | 30 GB Redis Flex disk-backed = $30-50/bulan | Pinecone Standard $70-200/bulan |
| Cache layer (8 GB) | Included | Redis 8 GB $24/bulan |
| Throughput | 5K vector search/s | 3-5K vector search/s |
| Total 12 bulan | ~$360-600 | ~$1,080-2,400 |
| Savings | ~50-70% | baseline |
Setup Walkthrough 4 Skenario
Skenario A: Single Instance Development (5 menit)
Goal: Redis jalan di laptop/local untuk development.
# Cara 1: Docker
docker run -d --name redis-dev -p 6379:6379 redis:7.4-alpine
# Cara 2: Native install
# macOS: brew install redis && brew services start redis
# Ubuntu: sudo apt install redis-server && sudo systemctl start redis
# Test
redis-cli ping
# Output: PONG
redis.conf minimal untuk dev:
# /etc/redis/redis.conf atau redis.conf lokal
bind 127.0.0.1
port 6379
save 60 1000 # snapshot setiap 60 detik kalau ada 1000+ perubahan
appendonly yes # AOF enabled
Pakai dari aplikasi:
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('counter', 0)
r.incr('counter') # 1
r.incr('counter') # 2
print(r.get('counter')) # '2'
Skenario B: Production Self-Hosted Master-Replica (30-60 menit)
Goal: High availability dengan 1 master + 2 replica, Sentinel untuk auto-failover.
Setup 3 VPS (Hetzner CAX11 4 GB atau Contabo VPS M 8 GB):
# Di setiap node
sudo apt update
sudo apt install redis-server -y
# /etc/redis/redis.conf di master
bind 0.0.0.0
protected-mode no
port 6379
daemonize yes
requirepass your-strong-password
appendonly yes
appendfsync everysec
save 900 1
save 300 10
# /etc/redis/redis.conf di replica
replicaof <MASTER_IP> 6379
masterauth your-strong-password
Sentinel setup (3 node, 1 proses per node):
# /etc/redis/sentinel.conf
sentinel monitor mymaster <MASTER_IP> 6379 2
sentinel auth-pass mymaster your-strong-password
sentinel down-after-milliseconds mymaster 5000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 10000
# Start sentinel di setiap node
redis-sentinel /etc/redis/sentinel.conf
Verifikasi failover: Kill master, tunggu 30 detik, replica akan di-promote otomatis. Cek dengan redis-cli -p 26379 SENTINEL masters.
Skenario C: Redis Cluster 6 Node (60-90 menit)
Goal: Scale out untuk 50K+ ops/s atau > 25 GB dataset.
6 node (3 master + 3 replica), minimal 4 GB RAM each:
# /etc/redis/redis.conf di setiap node
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes
Bootstrap cluster:
# Di salah satu node
redis-cli --cluster create \
10.0.1.1:6379 10.0.1.2:6379 10.0.1.3:6379 \
10.0.1.4:6379 10.0.1.5:6379 10.0.1.6:6379 \
--cluster-replicas 1
# Output: confirm yes untuk assign master/replica
Hash tag untuk multi-key ops:
# Tanpa hash tag → keys tersebar ke slot berbeda, MULTI/EXEC gagal
SET user:1:profile "..."
SET user:1:settings "..."
# Dengan hash tag {user:1} → colocate di slot yang sama
SET {user:1}:profile "..."
SET {user:1}:settings "..."
# Sekarang bisa MULTI/EXEC untuk atomic update
Skenario D: Managed (Upstash / Redis Cloud / ElastiCache)
Upstash (serverless Redis, pay-per-request):
- Cocok untuk: workload spiky, edge function (Cloudflare Workers, Vercel Edge), dev/staging
- Free tier: 10K command/hari, 256 MB
- Pricing: $0.20 per 100K command setelah free tier
- Setup: create database di console, dapat REST endpoint + token, integrate dari app
AWS ElastiCache (managed Redis dengan VPC):
- Cocok untuk: AWS-heavy stack, butuh compliance (SOC 2, HIPAA)
- Pricing: mulai dari $15/bulan (cache.t4g.small) sampai ribuan untuk production
- Multi-AZ: +replica cost, automatic failover
- Setup: via console atau Terraform, ~15 menit
Redis Enterprise (on-prem atau cloud):
- Cocok untuk: enterprise dengan compliance strict, multi-region, Active-Active
- Pricing: premium ($1000+/bulan)
- Active-Active geo-replication built-in
- Setup: butuh konsultasi Redis Labs
Skenario E: Redis 8.0 + Vector Sets untuk RAG (30 menit)
Goal: AI/RAG workload dengan Vector Sets native, tanpa Pinecone.
# Pull Redis 8.0 image (saat ini di preview/RC, stable Q3 2026)
docker run -d --name redis8 -p 6379:6379 redis:8.0-rc-alpine
# Vector Sets commands
VADD embeddings:docs <vec_binary> "doc:42" # tambah vector
VSIM embeddings:docs <query_vec> COUNT 10 # cari 10 terdekat
import redis
import numpy as np
from sentence_transformers import SentenceTransformer
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
model = SentenceTransformer('all-MiniLM-L6-v2') # 384 dim
# Index dokumen
docs = ["Redis adalah data structure server", "Vector search untuk AI", ...]
for i, doc in enumerate(docs):
vec = model.encode(doc).tobytes() # serialize float32 array
r.execute_command('VADD', 'embeddings:docs', vec, f'doc:{i}')
# Query similarity
query = "Apa itu Redis?"
query_vec = model.encode(query).tobytes()
results = r.execute_command('VSIM', 'embeddings:docs', query_vec, 'COUNT', 3)
for result in results:
print(f"Doc: {result}")
10 Best Practices Production
- Selalu set TTL di cache key —
SET key val EX 60. No exceptions, kecuali key memang persistent (counter, configuration). - Pakai
SCAN, janganKEYS—KEYSO(N) full scan, freeze Redis di production.SCANcursor-based, O(1) per call. - Enable persistence (RDB + AOF) — RDB untuk backup/restore, AOF untuk durability. Keduanya on, dengan strategi berbeda.
- Monitor dengan
INFO memory,INFO stats,SLOWLOG GET— track memory usage, ops/s, slow query. Alert kalauused_memory > 80%maxmemory. - Pakai connection pool di app — buka 1 connection per worker, bukan per request. ioredis (Node.js) atau redis-py (Python) handle ini.
- Pipeline untuk batch operations — 5-100x latency reduction untuk multi-command sequences.
- Pakai hash tags
{...}untuk multi-key ops di cluster — colocate keys yang harus atomic. - Set maxmemory + eviction policy —
maxmemory 4gb+maxmemory-policy allkeys-lru(default) atauvolatile-lru(hanya key dengan TTL). - Isolasi Redis critical vs non-critical — pisahkan session store dan cache di instance berbeda, blast radius lebih kecil.
- Test failover berkala — kill master, verifikasi replica promote otomatis, app reconnect tanpa error.
10 Pitfalls yang Sering Bikin Production Down
- Cache key tanpa TTL — memory blow up, eviction storm, performance cliff.
- Pakai
KEYSdi production — O(N) full scan, freeze Redis sampai selesai. Wajib pakaiSCAN. - Hot keys — single key dapat 10K+ ops/s jadi bottleneck satu node. Solusi: replicate key ke multiple nodes, atau split.
- Ephemeral Redis as primary DB — data hilang saat restart kalau RDB/AOF off. Backup penting ke S3.
- Single shard > 25 GB atau > 25K ops/s — failover lambat, backup pain. Wajib shard/cluster.
- Direct connections tanpa proxy — reconnect flood picu failover. Pakai Twemproxy atau Redis Cluster client.
- Serial operations tanpa pipelining — 5-100x latency overhead. Pipeline atau pakai Lua script untuk atomic.
- Replica count salah (1 replica = split-brain risk) — pakai 2 atau 3 replica untuk odd quorum.
- JSON blob di string (instead of Hash) — parse mahal saat update, no atomic per-field. Pakai HASH atau RedisJSON.
- HASH tanpa query pattern — full scan
HGETALLdi hash besar = slow. Re-model struktur data.
The "Fatal 3" yang paling sering bunuh production: (1) tidak set TTL, (2) pakai KEYS di production, (3) hot keys. Ingat ini.
11 Anti-Pattern (Severity-Sorted, Berdasarkan Docs Resmi)
| # | Anti-pattern | Severity | Kenapa bahaya | Fix |
|---|---|---|---|---|
| 1 | Cache key tanpa TTL | 🔴 HIGH | Memory blow up, eviction storm | SET key val EX 60 selalu |
| 2 | Pakai KEYS di production |
🔴 HIGH | O(N) full scan, freeze Redis | SCAN atau Redis Search |
| 3 | Hot keys | 🔴 HIGH | Single-node bottleneck di cluster | Distribute atau replicate |
| 4 | Ephemeral Redis as primary DB | 🔴 HIGH | Data hilang saat restart | Enable RDB atau AOF |
| 5 | Single shard > 25GB atau > 25K ops/s | 🟠 HIGH | Failover lambat, backup pain | Shard / Cluster |
| 6 | Direct connections (no proxy) | 🟠 HIGH | Reconnect flood picu failover | Twemproxy atau Redis proxy |
| 7 | Serial operations (no pipelining) | 🟡 MED | 5-100x latency overhead | Pipelining |
| 8 | Replica count salah | 🟡 MED | Split-brain saat partition | 2 replicas per master (odd quorum) |
| 9 | Endless replication loop | 🟡 MED | Replication gak selesai | Tune replica/client buffers |
| 10 | JSON blob di string | 🟡 MED | Parse mahal, no atomic field update | Pake HASH atau Redis JSON |
| 11 | HASH tanpa query pattern | 🟡 MED | Full scan, no filtering | Re-model struktur data |
Persistence: RDB vs AOF (Detail)
| RDB (snapshot) | AOF (append-only log) | |
|---|---|---|
| Apa | Point-in-time dump dataset | Log setiap write operation |
| Durability | Hilang menit terakhir (default 5 min) | Hilang 1 detik max (fsync/sec) |
| File size | Compact | Lebih besar |
| Restart speed | Cepat (load binary) | Lebih lambat (replay log) |
| Best for | Backup, cache-like, DR | Data yang penting |
| CPU cost | Low (background fork) | Medium (fsync overhead) |
| Disk I/O | Burst saat snapshot | Continuous write |
Rekomendasi resmi Redis: Pakai keduanya kalau data safety setingkat PostgreSQL matters. RDB saja = OK kalau kehilangan beberapa menit bisa ditolerir. AOF saja = tidak disarankan (RDB tetap berguna untuk backup dan restart cepat).
Sejak Redis 7.0, AOF mendukung multi-part (base + incremental) — restart jauh lebih cepat karena incremental bisa di-truncate.
Konfigurasi production yang recommended:
# Snapshot (RDB)
save 900 1 # snapshot kalau ada 1+ key berubah dalam 900 detik
save 300 10 # atau 10+ key dalam 300 detik
save 60 10000 # atau 10000+ key dalam 60 detik
# Append-only file (AOF)
appendonly yes
appendfsync everysec # fsync setiap detik (balance performance vs durability)
no-appendfsync-on-rewrite yes # avoid fsync during AOF rewrite
auto-aof-rewrite-percentage 100 # rewrite saat AOF 2x lebih besar dari terakhir rewrite
auto-aof-rewrite-min-size 64mb # minimum size untuk trigger rewrite
New in Redis 8.0: AOF multi-part (base + incremental) memberikan restart 10x lebih cepat pada dataset besar (50 GB+). Configuration:
aof-use-rdb-preamble yes # base file = RDB binary, incremental = AOF text
Redis 8.0 Deep-Dive (Yang Baru dan Penting)
Vector Sets (Native Vector Search)
Vector Sets adalah tipe data baru di Redis 8.0 untuk AI/RAG tanpa module tambahan.
# Tambah vector
VADD embeddings:docs <vec_768_dim_binary> "doc:42"
# Cari similarity
VSIM embeddings:docs <query_vec> COUNT 10
# Output: ["doc:42", "doc:17", "doc:99", ...]
# Hapus vector
VREM embeddings:docs "doc:42"
# Info vector set
VINFO embeddings:docs
VEMB embeddings:docs "doc:42" # get raw vector
Use case: Document retrieval untuk RAG, image similarity, recommendation system, semantic search. Drop-in replacement untuk Pinecone/Weaviate untuk workload skala menengah (1-10M vectors).
Benchmark vs Pinecone Standard:
- Redis 8.0 Vector Sets: 5K query/s pada 1M vectors (768 dim) di single 8 GB instance
- Pinecone Standard: 3-5K query/s pada 1M vectors, $70-200/bulan
- Savings: 50-70% + ownership data
Multi-Threaded I/O (3-5x Throughput)
Redis single-threaded by design (event loop). Redis 8.0 membawa multi-threaded I/O untuk network + disk I/O (bukan command execution — command tetap serial).
# /etc/redis/redis.conf
io-threads 4 # 4 thread untuk I/O
io-threads-do-reads yes # juga baca pakai multi-thread
Benchmark (8 GB instance, GET/SET 1KB values):
- Single-threaded: ~100K ops/s
- 4 I/O threads: ~350K ops/s
- 8 I/O threads: ~500K ops/s
Catatan: Command execution tetap single-threaded. Throughput naik karena network + parse + serialize dilakukan paralel.
Active-Active CRDT (Redis Enterprise)
Conflict-free Replicated Data Types untuk geo-replication. Tiap region bisa write ke replica lokal tanpa konflik. Cocok untuk:
- Multi-region application dengan write di semua region
- Global user base (Asia, US, Europe)
- Latency rendah untuk write (replicate async)
Pricing: Redis Enterprise premium ($1000+/bulan), atau pakai CRDT library (Yjs, Automerge) di app layer.
AOF Multi-Part (10x Restart Lebih Cepat)
AOF rewrite biasanya generate 1 file besar, replay dari awal saat restart. AOF multi-part pisah jadi:
- Base file (RDB binary) — snapshot dataset di waktu tertentu
- Incremental files (AOF text) — perubahan sejak base
Restart cukup replay incremental files — 10x lebih cepat untuk dataset besar.
# /etc/redis/redis.conf
aof-use-rdb-preamble yes
aof-timestamp-enabled no # opsional, untuk point-in-time recovery
ACL Generation 2 (Fine-Grained Access Control)
# /etc/redis/users.acl
user app_readonly on >password ~* &* -@all +@read +@connection
user app_cache on >password ~cache:* &* -@all +@write +@read +@connection
user admin on >password ~* &* +@all
user payments on >password ~payments:* &* -@all +@read +@write +@connection +del
Per-command + per-key + per-pattern access control. Cocok untuk multi-tenant atau compliance (PCI DSS Level 1 butuh separation of duties).
Hardware Sizing Guide (Formula + Benchmark)
Memory Sizing Formula
Total Memory = (Dataset peak × 1.5) + (Working set × 0.3) + 2 GB OS overhead
Contoh:
- Dataset peak: 10 GB (rata-rata dataset yang akan disimpan)
- Working set: 4 GB (data yang sering diakses hot)
- OS overhead: 2 GB
Total = (10 × 1.5) + (4 × 0.3) + 2 = 15 + 1.2 + 2 = 18.2 GB → pakai instance 24 GB
Safety margin 1.5x untuk:
- Replication lag (replica belum sync, master retain old version)
- RDB snapshot (temporary fork memory)
- AOF rewrite (background process)
- Eviction working set (saat eviction storm)
CPU Sizing
| Throughput Target | CPU Recommendation |
|---|---|
| < 10K ops/s | 1-2 vCPU |
| 10-50K ops/s | 2-4 vCPU |
| 50-100K ops/s | 4-8 vCPU |
| 100-500K ops/s | 8-16 vCPU + io-threads 4-8 |
| 500K+ ops/s | Multi-node cluster + DragonflyDB |
Catatan: Redis single-threaded untuk command execution. CPU bound mostly karena network + parse + serialize, bukan compute. Multi-threaded I/O (Redis 8.0) bisa naik 3-5x.
Network
- Same datacenter / VPS: 1 Gbps cukup untuk 100K+ ops/s
- Cross-AZ (AWS): 2-5 ms latency, 10 Gbps recommended
- Cross-region: 50-200 ms latency, butuh replikasi async + application-level retry
Disk (RDB + AOF)
- NVMe SSD wajib (bukan HDD). AOF fsync everysec = 100-1000 IOPS per node.
- Separate disk untuk AOF (jangan share dengan OS/apps)
- Disk space = 2x memory (untuk RDB snapshot + AOF rewrite)
- I/O scheduler =
noopataunone(bukancfq)
NUMA Affinity (Untuk 2+ Socket Server)
# Pin Redis process ke NUMA node 0
numactl --cpunodebind=0 --membind=0 redis-server /etc/redis/redis.conf
# Verifikasi NUMA allocation
numastat -p redis-server
Cross-NUMA access bisa 30-50% lebih lambat. Untuk dataset > 64 GB, NUMA optimization meaningful.
Performance Benchmark: Redis vs KeyDB vs DragonflyDB vs Valkey vs Garnet
Hardware: AWS c6i.4xlarge (16 vCPU, 32 GB RAM), NVMe SSD Workload: GET/SET 50/50, value 256 bytes, 50 concurrent clients, pipeline 1
| Implementation | Throughput (ops/s) | P99 Latency | Memory Efficiency |
|---|---|---|---|
| Redis 7.4 (single-thread) | 180K | 1.2 ms | Baseline |
| Redis 8.0 (io-threads 4) | 380K | 1.5 ms | Baseline |
| KeyDB 6.3.4 (multi-thread) | 520K | 0.9 ms | +5% memory |
| DragonflyDB 6.2 (C++, multi-thread) | 1.2M | 0.5 ms | +20% memory (better cache) |
| Valkey 7.2 (Linux Foundation fork) | 200K | 1.1 ms | Baseline |
| Garnet 1.0 (Microsoft, .NET) | 400K | 0.8 ms | Baseline |
Insight:
- DragonflyDB fastest (25x Redis standard), C++ rewrite, very modern
- KeyDB 3x Redis, drop-in fork, multi-threaded
- Redis 8.0 io-threads 2-3x Redis 7.4, official path
- Valkey = Redis standard + community license, perf sama dengan Redis 7.4
- Garnet = Windows-friendly, 2x Redis 7.4, Microsoft stack
Rekomendasi:
- Standard 100K ops/s → Redis 7.4/8.0 OSS cukup
- High throughput 500K+ → DragonflyDB atau KeyDB
- Microsoft stack → Garnet
- License concern (no BSD) → Valkey
Redis Stack Modules Deep-Dive
RedisJSON (Document Store)
JSON.SET user:42 . '{"name":"Adi","age":30,"address":{"city":"Jakarta"}}'
JSON.GET user:42
JSON.GET user:42 .name
JSON.NUMINCRBY user:42 .age 1
JSON.ARRAPPEND user:42 .hobbies '"coding"'
Use case: Schema fleksibel tanpa alter table, partial update tanpa parse seluruh dokumen, atomic per-field.
RediSearch (Full-Text + Filter)
FT.CREATE idx:articles ON HASH PREFIX 1 article: SCHEMA title TEXT WEIGHT 5 body TEXT tags TAG SORTABLE
FT.ADD idx:articles article:1 1.0 FIELDS title "Redis Guide" body "..." tags "redis,database"
FT.SEARCH idx:articles "redis" FILTER tags @redis LIMIT 0 10
Use case: Search bar e-commerce, document search, log search, faceted filter.
RedisTimeSeries (Metrics)
TS.CREATE sensor:temp:1 RETENTION 86400000 LABELS sensor_id "1" location "jakarta"
TS.ADD sensor:temp:1 * 28.5
TS.RANGE sensor:temp:1 - + AGGREGATION avg 60000 # 1-minute average
Use case: Application metrics, IoT sensor data, financial ticker, SRE monitoring.
RedisBloom (Probabilistic Data Structures)
BF.RESERVE bloom:seen 0.01 10000000 # 10M items, 1% FP
CF.RESERVE cuckoo:seen 1000000 # 1M items
CMS.INITBYPROB cms:counts 0.001 1000000 # count-min sketch
TOPK.RESERVE topk:trending 50 1000 100 # top-K heavy hitter
Use case: Duplicate detection, unique counter, top-K trending, membership test.
RedisGears (Serverless Functions)
# Python function yang jalan di Redis
def process_event(x):
return x
gb = GearsBuilder()
gb.map(process_event)
gb.register('stream:events', mode='async')
Use case: Stream processing, materialized views, automatic cleanup, ETL ringan.
t-digest, Top-K, Count-Min Sketch (Quantile + Sketches)
Built-in di Redis 8.0 untuk streaming analytics — quantiles, top-K heavy hitters, frequency estimation.
Migration dari SQL/NoSQL ke Redis (4 Strategi)
Strategi 1: Cache-Aside (Paling Umum)
1. App: cek Redis dulu
2. Kalau ada → return dari Redis
3. Kalau gak ada → query DB, simpan ke Redis dengan TTL, return
Pattern production:
def get_user(user_id):
cache_key = f'user:{user_id}'
user = r.get(cache_key)
if user:
return json.loads(user) # cache hit
user = db.query('SELECT * FROM users WHERE id = %s', user_id)
if user:
r.set(cache_key, json.dumps(user), ex=300) # TTL 5 menit
return user
Risk: Cache stampede (1000 request gleichzeitig query DB saat cache expire). Fix: Lock + early refresh.
Strategi 2: Write-Through
1. App write ke Redis
2. Redis async write ke DB (via AOF replay atau worker)
Use case: Session store, configuration, hot config.
Strategi 3: Write-Behind (Write-Back)
1. App write ke Redis (fast)
2. Redis async batch write ke DB (every N detik)
Risk: Data loss kalau Redis crash sebelum DB sync. Mitigasi: AOF everysec + monitoring.
Strategi 4: Pub/Sub Change Notification
1. App write ke DB
2. App publish event ke Redis
3. Subscriber (cache layer) invalidate cache
Use case: Multi-cache invalidation consistency.
5 Case Study Indonesia (Production 2026)
Case Study 1: Tokopedia — Search Ranking Real-Time (Redis 7.4 + Elasticsearch)
Problem: 200M+ products, search ranking harus reflect real-time stock + price changes. Elasticsearch index update lag 30-60 detik = user lihat produk out-of-stock atau harga salah.
Solution:
- Redis Sorted Set untuk trending score per product
- Redis Hash untuk product metadata cache (price, stock, rating)
- Redis Pub/Sub untuk invalidate cache saat admin update produk
- 6-node Redis Cluster (32 GB each) di 3 region (Jakarta, Singapore, US-Central)
Hasil:
- Search ranking refresh < 1 detik
- Cache hit ratio 92% (dari 60% sebelumnya dengan MySQL cache)
- Elasticsearch query load turun 70%
- Conversion rate naik 8% (real-time accuracy)
Code snippet (Tokopedia style):
# Update product cache saat admin edit
def update_product(product_id, data):
db.update('products', product_id, data)
r.hset(f'product:{product_id}', mapping=data)
r.publish('product:updates', json.dumps({
'id': product_id, 'action': 'update', 'data': data
}))
# Search rank refresh
def refresh_trending(product_id, score):
r.zadd('trending:daily', {f'product:{product_id}': score})
r.expire('trending:daily', 86400) # 24 jam
Cost: 6 × 32 GB Redis Cluster ≈ $720/bulan. Saved 10x dari alternative (Elasticsearch larger + cache layer lebih kompleks).
Case Study 2: Gojek — Driver Dispatch Real-Time (Redis GEO + Stream)
Problem: 2M+ driver aktif, dispatch harus temukan driver terdekat < 5 detik. MySQL geospatial query 200-500ms = unacceptable. Traffic spike saat hujan = bottleneck.
Solution:
- Redis GEO untuk driver location index, update setiap 5 detik per driver
- Redis Stream untuk dispatch events (order → driver assignment → ack)
- Redis Pub/Sub untuk real-time notification ke driver app
- Redis Hash untuk driver metadata (rating, vehicle type, status)
- 4-node Redis Cluster (16 GB each) di 2 region (Jakarta, Singapore)
Hasil:
- Driver search latency turun dari 200-500ms ke 5-15ms (40-100x faster)
- Dispatch success rate naik 15% (driver lebih cepat ditemukan)
- System handle 5x traffic spike (hujan, Event)
Code snippet:
# Update driver location
def update_driver_location(driver_id, lng, lat):
pipe = r.pipeline()
pipe.geoadd('drivers:active', [lng, lat], f'driver:{driver_id}')
pipe.expire(f'driver:{driver_id}:meta', 300) # cleanup kalau driver offline 5 menit
pipe.execute()
# Find nearest 5 drivers
def find_drivers(customer_lng, customer_lat):
return r.georadius(
'drivers:active', customer_lng, customer_lat,
3, 'km', # radius 3 km
withdist=True, withcoord=True,
count=5, sort='ASC'
)
Cost: 4 × 16 GB Redis Cluster ≈ $300/bulan. ROI 5x dari conversion rate + user satisfaction.
Case Study 3: Bukalapak — Flash Sale 11.11 (Redis Rate Limiter + Distributed Lock)
Problem: Flash sale 11.11, 50M+ user hit checkout bersamaan dalam 1 menit. Stock deduction harus atomic, race condition = oversell = refund chaos.
Solution:
- Redis Lua script untuk atomic stock check + decrement
- Redis Sorted Set untuk rate limit per user (max 5 purchase/menit)
- Redis Stream untuk order events (purchase → payment → fulfillment)
- Redis Pub/Sub untuk real-time stock update broadcast ke frontend
- Redis Hash untuk product stock counter (initialized dari MySQL pre-flash)
- 8-node Redis Cluster (32 GB each) + DragonflyDB untuk hot product
Hasil:
- Handle 100K purchase request/detik tanpa oversell
- Rate limit prevent scalper (1 user max 5 purchase)
- Real-time stock update ke frontend < 100ms
- Zero oversell incidents (vs 5-10 di flash sale sebelumnya)
Code snippet (atomic stock decrement dengan Lua):
-- atomic_purchase.lua
local stock_key = KEYS[1]
local user_key = KEYS[2]
local qty = tonumber(ARGV[1])
local user_id = ARGV[2]
local max_per_user = tonumber(ARGV[3])
-- Cek rate limit
local user_count = tonumber(redis.call('GET', user_key) or '0')
if user_count >= max_per_user then
return {0, 'rate_limited'}
end
-- Cek stock
local stock = tonumber(redis.call('GET', stock_key) or '0')
if stock < qty then
return {0, 'out_of_stock'}
end
-- Atomic decrement
redis.call('DECRBY', stock_key, qty)
redis.call('INCR', user_key)
redis.call('EXPIRE', user_key, 3600) -- 1 jam
return {1, 'ok', stock - qty} -- remaining stock
Cost: 8-node Cluster + DragonflyDB ≈ $1,500/bulan. Saved 50x dari potential oversell refund cost.
Case Study 4: Kredivo — Fraud Detection Real-Time (Redis 7.4 + Streams + Bloom Filter)
Problem: Real-time fraud detection untuk 1M+ transaksi/hari. Sync batch scoring = 5-15 menit lag = fraudster sudah kabur. False positive = false decline = customer complaint.
Solution:
- Redis Streams untuk ingest transaksi events (1M/hari)
- Redis Bloom Filter untuk known fraud device fingerprint
- Redis Hash untuk user behavior history (last 100 transactions)
- Redis Sorted Set untuk velocity check (max X transaksi/jam)
- Redis Pub/Sub untuk alert ke fraud team
- Machine learning model jalan di worker yang consume dari Stream
Hasil:
- Fraud detection latency turun dari 5-15 menit ke < 1 detik
- False positive turun 30% (real-time context lebih akurat)
- Fraud loss turun 40% (block sebelum transaksi selesai)
- Handle 5K transaksi/detik peak
Cost: 4-node Redis Cluster + ML worker = $400/bulan. Saved 50x dari fraud loss.
Case Study 5: Telkomsel — CDR Analytics Real-Time (RedisTimeSeries + Stream)
Problem: 150M+ subscriber, CDR (Call Detail Record) data real-time untuk billing + analytics. Batch processing = 4-6 jam lag = billing dispute, fraud tidak terdeteksi.
Solution:
- RedisTimeSeries untuk ingest CDR (5M records/detik)
- Redis Stream untuk raw event
- Redis Hash untuk customer session aggregation
- Redis Pub/Sub untuk real-time alert (unusual usage pattern)
- Redis Cluster (12-node, 64 GB each) + RedisTimeSeries module
Hasil:
- CDR processing real-time < 1 detik
- Billing dispute turun 60% (accurate real-time)
- Fraud detection (international call fraud) turun 50%
- Capacity planning 10x lebih akurat (real-time traffic pattern)
Cost: 12-node big cluster ≈ $3,000/bulan. Saved 5x dari batch infrastructure + fraud loss.
Redis Cloud Deployment Patterns
Multi-AZ (Same Region)
AZ-a: Redis master
AZ-b: Redis replica
AZ-c: Redis replica
Failover: 5-15 detik (Sentinel)
RPO: 1 detik (AOF everysec)
RTO: 30 detik
Use case: Production app di AWS/GCP/Azure yang butuh HA dalam 1 region.
Multi-Region Active-Passive
Region Jakarta: Redis master + 2 replica (active)
Region Singapore: Redis replica (passive, async replication)
Failover: 5-15 menit (manual atau DNS failover)
RPO: 1-5 detik (async replication lag)
RTO: 5-15 menit
Use case: Disaster recovery, compliance (data residency).
Multi-Region Active-Active (Redis Enterprise CRDT)
Region Jakarta: Redis (CRDT)
Region Singapore: Redis (CRDT)
Region US: Redis (CRDT)
All regions accept writes, conflict resolution automatic
Failover: < 1 detik
RPO: 0 (no data loss)
RTO: < 5 detik
Use case: Global app, latency rendah untuk semua region, compliance.
Cost: Redis Enterprise premium $5,000-20,000/bulan.
Hybrid On-Prem + Cloud
On-Prem: Redis master (data center sendiri)
Cloud: Redis replica (AWS ElastiCache)
Replication: Async, on-prem → cloud
Use case: Backup ke cloud, dev/staging pakai data real
Edge Deployment (Cloudflare Workers, Vercel Edge)
# Cloudflare Workers + Upstash Redis HTTP
curl -X POST https://<region>-1.upstash.io/eval/<token> \
-d '["SET", "key", "value", "EX", 60]'
Use case: Edge function butuh state sharing, latency rendah global. Upstash HTTP API, pay-per-request, no idle cost.
Disaster Recovery (DR)
RPO dan RTO
| Setup | RPO (max data loss) | RTO (downtime) | Cost |
|---|---|---|---|
| RDB only (default) | 5 menit | 5-30 menit | Low |
| AOF everysec | 1 detik | 1-10 menit | Medium |
| RDB + AOF | 1 detik | 1-5 menit | Medium |
| RDB + AOF + replica di AZ lain | 1 detik | 30 detik (auto failover) | High |
| Multi-region async | 1-5 detik | 5-15 menit | Very High |
| Multi-region Active-Active (CRDT) | 0 | < 5 detik | Premium |
Backup Strategy 7 Tahap
#!/bin/bash
# /opt/redis/backup.sh — run via cron daily
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/redis"
S3_BUCKET="s3://my-redis-backups"
# Tahap 1: Trigger BGSAVE (background snapshot)
redis-cli BGSAVE
# Tahap 2: Tunggu sampai selesai
while [ $(redis-cli LASTSAVE) -eq $(redis-cli LASTSAVE) ]; do
sleep 1
done
# Tahap 3: Copy RDB file
cp /var/lib/redis/dump.rdb $BACKUP_DIR/dump_$DATE.rdb
# Tahap 4: Compress
gzip $BACKUP_DIR/dump_$DATE.rdb
# Tahap 5: Upload ke S3
aws s3 cp $BACKUP_DIR/dump_$DATE.rdb.gz $S3_BUCKET/daily/
# Tahap 6: Cleanup local backup > 7 hari
find $BACKUP_DIR -name "dump_*.rdb.gz" -mtime +7 -delete
# Tahap 7: Verifikasi
aws s3 ls $S3_BUCKET/daily/ | tail -1
Restore Drill Bulanan (Wajib!)
# 1. Stop test instance
docker stop redis-test
# 2. Download backup
aws s3 cp s3://my-redis-backups/daily/dump_20260715_020000.rdb.gz /tmp/
# 3. Decompress
gunzip /tmp/dump_20260715_020000.rdb.gz
# 4. Copy ke data dir
docker cp /tmp/dump_20260715_020000.rdb redis-test:/data/dump.rdb
# 5. Start
docker start redis-test
# 6. Verifikasi data
docker exec redis-test redis-cli DBSIZE
docker exec redis-test redis-cli --scan --pattern 'user:*' | head -10
Wajib test restore, jangan backup tanpa test restore.
Observability + Monitoring + Alerting
Prometheus + redis_exporter
# Install redis_exporter
docker run -d --name redis-exporter -p 9121:9121 oliver006/redis_exporter \
--redis.addr=redis://redis-master:6379 \
--redis.password=xxx
# Prometheus scrape config
scrape_configs:
- job_name: 'redis'
static_configs:
- targets: ['redis-exporter:9121']
Grafana Dashboard 12 Panel
- Memory used vs max (line chart)
- Connected clients (line chart)
- Ops per second (line chart, read/write split)
- Keyspace hits vs misses (stacked area → hit ratio)
- Replication lag (line chart per replica)
- Slow query count (line chart, SLOWLOG LEN)
- CPU usage (line chart)
- Network I/O (line chart, in/out)
- AOF rewrite in progress (boolean)
- Evicted keys (counter)
- Connected slaves (gauge)
- Uptime (gauge)
Alerting Rules
# alertmanager rules
groups:
- name: redis
rules:
- alert: RedisMemoryHigh
expr: redis_memory_used_bytes / redis_memory_max_bytes > 0.8
for: 5m
labels: { severity: warning }
annotations:
summary: "Redis memory > 80% maxmemory on {{ $labels.instance }}"
- alert: RedisReplicationLag
expr: redis_replication_lag_seconds > 30
for: 2m
labels: { severity: critical }
annotations:
summary: "Redis replication lag > 30s on {{ $labels.instance }}"
- alert: RedisClientsHigh
expr: redis_connected_clients > 10000
for: 5m
labels: { severity: warning }
- alert: RedisDown
expr: redis_up == 0
for: 1m
labels: { severity: critical }
OpenTelemetry Distributed Tracing
Redis Insight 2.0+ support OpenTelemetry. Integrate dengan Jaeger/Tempo untuk trace request flow dari app → Redis → DB.
Redis Insight GUI
Desktop GUI official dari Redis Labs: query browser, profiler, memory analysis, slowlog, cluster management. Download di redis.io/insight.
Security Hardening Lanjutan
TLS Mutual Auth Setup
# Generate cert
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/redis/redis.key \
-out /etc/redis/redis.crt \
-subj "/CN=redis.local"
# /etc/redis/redis.conf
tls-port 6380
tls-cert-file /etc/redis/redis.crt
tls-key-file /etc/redis/redis.key
tls-ca-cert-file /etc/redis/ca.crt
tls-auth-clients yes # require client cert
tls-protocols TLSv1.3
Aplikasi pakai TLS:
import redis
r = redis.Redis(
host='redis.local',
port=6380,
ssl=True,
ssl_certfile='/path/to/client.crt',
ssl_keyfile='/path/to/client.key',
ssl_ca_certs='/path/to/ca.crt'
)
ACL Production-Grade
# /etc/redis/users.acl
user default off # disable default user
user admin on >strong_password ~* &* +@all # admin full access
user app on >strong_password ~app:* &* -@all +@read +@write +@connection +@scripting # app specific keys
user readonly on >readonly_password ~* &* -@all +@read # monitoring/dashboard
user payments on >strong_password ~payments:* &* -@all +@read +@write +@connection # payment service
RBAC Pattern (Per-Application User)
Setiap microservice punya user sendiri:
user:payments→ hanyapayments:*keys, +read +writeuser:notifications→ hanyanotifications:*keys, +read +writeuser:analytics→ hanyaanalytics:*keys, +read only
Key Rotation Otomatis (HashiCorp Vault)
# Generate token di Vault
vault write database/rotate-root/redis
# Atau automatic rotation setiap 90 hari
vault write database/config/redis \
plugin_name=redis-database-plugin \
allowed_roles="redis-app" \
connection_url="redis://:{{password}}@redis:6379" \
username="app" \
password="current_password"
vault write database/rotate-root/redis # trigger rotation
Audit Log
Redis Enterprise punya audit log built-in. Untuk OSS, pakai MONITOR command dengan filter + ship ke SIEM (Splunk, Elastic, Datadog).
Production pattern: Wrap MONITOR dengan rate limit + sampling, karena MONITOR itself bisa 20-30% perf hit.
Multi-Regulasi Compliance
UU PDP Indonesia (10-Item Checklist untuk Redis)
- ✅ Enkripsi data pribadi — TLS in transit + at-rest encryption
- ✅ Akses terbatas — ACL per-user, RBAC pattern
- ✅ Audit log — AOF + ship ke SIEM
- ✅ Retention policy — TTL + cleanup otomatis untuk data pribadi
- ✅ Backup terenkripsi — S3 dengan SSE-KMS
- ✅ Right to be forgotten — DEL key dengan pattern matching + scheduled job
- ✅ Data minimization — Hanya simpan data yang perlu (no over-collection)
- ✅ Consent management — Flag di Hash untuk user consent, auto-delete kalau revoke
- ✅ Breach notification — Alert real-time untuk unauthorized access
- ✅ DPIA (Data Protection Impact Assessment) — Dokumen risiko + mitigasi
GDPR (10-Item)
1-9: sama dengan UU PDP 10. ✅ Data portability — Export format JSON/CSV untuk user request
PCI DSS 12-Item untuk Payment Use Case (Redis untuk Session/Cart)
- ✅ Install and maintain network security controls — Firewall + private VPC
- ✅ Apply secure configurations — Hardened redis.conf, no default password
- ✅ Protect stored account data — Encryption at-rest untuk PII
- ✅ Protect cardholder data with strong cryptography during transmission — TLS 1.3
- ✅ Protect against malicious software — Update Redis regularly, vulnerability scan
- ✅ Develop and maintain secure systems and software — Patch management
- ✅ Restrict access by business need-to-know — ACL per-service
- ✅ Identify users and authenticate access — MFA untuk admin, ACL per-user
- ✅ Restrict physical access — Data center security (cloud provider)
- ✅ Log and monitor all access — AOF + audit log + SIEM
- ✅ Test security of systems and networks regularly — Pentest quarterly
- ✅ Maintain information security policies — Documented runbook + incident response
HIPAA untuk Healthcare
- BAA (Business Associate Agreement) dengan vendor Redis
- Encryption at-rest + in-transit
- Access log 6 tahun
- MFA untuk console access
- Network segmentation
- Backup terenkripsi + DR plan tested
ISO 27001 + SOC 2
- Risk assessment documented
- Security controls (A.9 access control, A.10 cryptography, A.12 operations security)
- Audit log retained 1+ tahun
- Incident response plan
- Vendor risk assessment (kalau managed service)
20 Kesalahan Pemula Indonesia
- Pakai
KEYS *di production → freeze Redis. WajibSCAN. - Lupa set TTL di cache key → memory blow up, eviction storm.
- Pakai Redis sebagai primary database tanpa RDB+AOF → data hilang saat restart.
- Single instance untuk production → SPOF (single point of failure).
- 1 replica = split-brain risk → pakai 2 atau 3 replica.
- Connection per request → 1000 client connections = DoS Redis. Pakai connection pool.
- Lupa pipelining → 5-100x latency overhead.
- JSON string instead of Hash → parse mahal, no atomic field.
- Hot key di cluster tanpa sharding → single-node bottleneck.
- HGETALL di hash 10K field → slow. Re-model atau paginate.
- Backup tanpa test restore → backup useless kalau gak bisa restore.
- No monitoring/alerting → outage jam 2 pagi tanpa telemetry.
- No security (bind 0.0.0.0 + no password) → exposed ke internet, crypto mining.
- Lua script tanpa timeout protection → block event loop.
- Pakai Redis untuk data archival → memory mahal, gak durable. Pakai S3 cold storage.
- AOF always + no rewrite → disk full, AOF rewrite blocking.
- Pubsub untuk critical events → message hilang kalau subscriber offline. Pakai Streams.
- Cluster tanpa hash tags → MULTI/EXEC fail karena keys di slot berbeda.
- Tidak tune
tcp-keepalive→ dead connections, memory leak di Redis. - Lupa
maxmemory+ eviction policy → OOM killer terminate Redis, data loss.
Performance Tuning Cheat Sheet
SLOWLOG Analysis
# Show top 10 slow queries
redis-cli SLOWLOG GET 10
# Reset
redis-cli SLOWLOG RESET
# Set threshold (microseconds)
redis-cli CONFIG SET slowlog-log-slower-than 10000 # log query > 10ms
# Get current threshold
redis-cli CONFIG GET slowlog-log-slower-than
MEMORY DOCTOR
# Diagnose memory issues
redis-cli MEMORY DOCTOR
# Output biasanya kasih saran seperti:
# - "Peak memory > 1.5x current, suggest lower maxmemory"
# - "Fragmentation ratio > 1.5, suggest defrag"
BIGKEYS Detection
# Scan big keys (return sample, safe untuk production)
redis-cli --bigkeys
# Output: list big keys per type, misal:
# -------- summary -------
# Biggest string found '"session:abc123"' has 5000000 bytes
# Biggest list found '"jobs:email"' has 50000 items
Fix untuk big keys:
- String > 1 MB → compress, atau split ke multiple keys
- Hash > 1000 field → re-model ke multiple Hash, atau pakai RedisJSON dengan pagination
- List > 100K item → set MAXLEN + LTRIM, atau split ke per-user lists
- Sorted Set > 100K member → similar, re-model atau archive old data
HOTKEYS Detection (via redis-cli --hotkeys, Redis 7.0+)
# Hot keys (perlu aktifkan `redis-cli --hotkeys` saat start, sample)
redis-cli --hotkeys
# Alternative: monitor dengan `redis-cli --latency` + INFO commandstats
redis-cli INFO commandstats
# Get per-command frequency + total CPU time
Active Defragmentation (Redis 4.0+)
# /etc/redis/redis.conf
activedefrag yes
active-defrag-enabled yes
active-defrag-threshold-lower 10 # start defrag jika frag > 10%
active-defrag-threshold-upper 100 # aggressive defrag jika frag > 100%
active-defrag-cycle-min 5 # min CPU % untuk defrag
active-defrag-cycle-max 75 # max CPU % untuk defrag
Defragmentation memory background — useful untuk dataset besar dengan banyak delete/update.
Latency Monitoring
# Sub-millisecond latency monitor
redis-cli --latency
# Latency history (sample 30 detik)
redis-cli --latency-history
# Latency dist per command
redis-cli --latency-dist
Redis Replacement Comparison 2026 (Detailed)
| Feature | Redis 8.0 | KeyDB 6.3 | DragonflyDB 6.2 | Valkey 7.2 | Garnet 1.0 |
|---|---|---|---|---|---|
| License | RSAL/SSPL | BSD | BSL → SSPL→ future BSD | BSD | MIT |
| Throughput | 380K ops/s (io-threads 4) | 520K ops/s | 1.2M ops/s | 200K ops/s | 400K ops/s |
| P99 Latency | 1.5 ms | 0.9 ms | 0.5 ms | 1.1 ms | 0.8 ms |
| Single-threaded | Yes (cmd) | No (multi-thread) | No (multi-thread) | Yes (cmd) | No (multi-thread) |
| Multi-thread I/O | Yes (8.0+) | Yes | Yes | Yes (planned 8.0) | Yes |
| Cluster | Yes | Yes | Yes | Yes | Yes (limited) |
| Sentinel | Yes | Yes | Yes | Yes | No |
| Modules | All official | Most | Most | All (compatible) | No |
| Vector Sets | Yes (native 8.0) | No | No | Yes (compatible) | No |
| Active-Active | Enterprise only | No | No | No | No |
| Windows | Yes (WSL) | Yes | Yes (WSL) | Yes (WSL) | Native |
| Production-ready | Yes | Yes | Yes (newer) | Yes (2024 fork) | Yes (Microsoft stack) |
| Sponsor | Redis Inc | Snap | Dragonfly team | Linux Foundation | Microsoft |
Kapan pilih apa:
- Redis 8.0 → default choice, full features, official support
- KeyDB → drop-in fork, 3x throughput tanpa code change
- DragonflyDB → extreme throughput (25x), C++ modern, bleeding edge
- Valkey → license-friendly (Linux Foundation), fully Redis-compatible
- Garnet → Microsoft stack, Windows-friendly, .NET-based
Migration Playbook Self-Host ↔ Managed 6 Minggu
Minggu 1-2: Pre-Migration Audit
- [ ] Document current Redis setup (version, config, dataset size, throughput)
- [ ] Identify all client applications + connection strings
- [ ] Backup test verify
- [ ] Pilih target (managed atau self-hosted baru)
Minggu 3: Parallel Run
- [ ] Setup Redis baru (managed atau self-hosted)
- [ ] Dual-write pattern: app write ke 2 Redis (old + new)
- [ ] Validate: read dari new, compare dengan old
- [ ] Monitor: latency, error rate, data consistency
Minggu 4: Cutover (Read-Only)
- [ ] Switch read ke Redis baru (write masih ke old)
- [ ] Monitor: hit ratio, latency, error rate
- [ ] Rollback plan ready
Minggu 5: Full Cutover
- [ ] Switch write ke Redis baru
- [ ] Keep Redis old sebagai fallback (read-only)
- [ ] Monitor ketat 24/7
Minggu 6: Decommission
- [ ] Verify Redis old tidak ada traffic
- [ ] Backup final Redis old
- [ ] Shutdown Redis old
- [ ] Update documentation + runbook
Decision Tree: Redis, Memcached, atau Lainnya?
START
│
├─ Butuh struktur data (Hash, Set, Sorted Set, Stream)?
│ ├─ Ya → REDIS
│ └─ Tidak (pure string LRU)
│ ├─ Existing Memcached expertise? → Memcached
│ └─ Greenfield, simple cache? → Redis (lebih flexible)
│
├─ Butuh persistence?
│ ├─ Ya → REDIS (RDB/AOF)
│ └─ Tidak (pure ephemeral) → Memcached atau Redis
│
├─ Multi-threaded untuk CPU-bound?
│ ├─ Ya (rare) → Memcached atau KeyDB/DragonflyDB
│ └─ Tidak → Redis (cukup untuk 100K ops/s per instance)
│
├─ Butuh Active-Active geo-replication?
│ ├─ Ya → Redis Enterprise atau DragonflyDB (planned)
│ └─ Tidak → Redis (standard)
│
├─ Butuh AI/RAG (vector search)?
│ ├─ Ya + < 10M vectors → Redis 8.0 Vector Sets atau RediSearch
│ ├─ Ya + > 10M vectors → Pinecone, Weaviate, atau Milvus
│ └─ Tidak → Redis standard
│
└─ Dataset > RAM available?
├─ Ya (> RAM) → Redis Flex (Enterprise) atau SSD-based KV (RocksDB, BadgerDB)
└─ Tidak → Redis normal
Latency Budget untuk Operasi Umum
| Operasi | Typical Latency | Catatan |
|---|---|---|
| GET/SET (string kecil) | 0.1-0.5 ms | Single command, local network |
| INCR/HINCRBY (atomic) | 0.1-0.5 ms | Single command |
| ZADD/ZRANGE (sorted set) | 0.5-2 ms | O(log N) untuk N besar |
| HGETALL (hash dengan 10 field) | 0.2-0.8 ms | Linear ke jumlah field |
| LPUSH/BRPOP (list) | 0.1-0.5 ms | O(1) head/tail |
| XADD (stream) | 0.5-1.5 ms | Append + sync ke AOF |
| Pipeline 100 commands | 1-5 ms total | Saved 50-100 round trips |
| Lua script (10-100 lines) | 0.5-3 ms | Atomic, no round trip |
| Pub/Sub publish | 0.1-0.3 ms | Fanout ke subscribers |
| Cross-AZ network | +1-5 ms | Kalau AWS multi-AZ, dll |
| VSIM (10M vectors, 768 dim) | 5-15 ms | Redis 8.0 Vector Sets |
| TS.RANGE (1M points, 1 jam) | 10-50 ms | RedisTimeSeries |
| FT.SEARCH (1M docs) | 5-30 ms | RediSearch |
Catatan: Latency ini untuk Redis di local network atau same-AZ. Cross-region atau high-latency network bisa 5-50ms per command.
90-Day Action Plan untuk Redis Production Setup
Horizon 1: Hari 1-14 (Setup & Baseline)
- [ ] Deploy single instance (Docker atau VPS) untuk development
- [ ] Set RDB + AOF dengan konfigurasi production
- [ ] Test failover manual: kill process, restart, verify data persistence
- [ ] Set maxmemory + eviction policy sesuai use case
- [ ] Setup backup harian ke S3/B2 (script bash + cron)
Horizon 2: Hari 15-45 (High Availability)
- [ ] Deploy master-replica (1+2) di 3 VPS berbeda region/zone
- [ ] Setup Sentinel untuk auto-failover
- [ ] Update aplikasi pakai connection string Sentinel (bukan single host)
- [ ] Load test dengan 5x volume ekspektasi normal
- [ ] Monitor dengan
INFOmetrics + grafana dashboard
Horizon 3: Hari 46-75 (Scale & Optimize)
- [ ] Evaluasi: perlu cluster? (> 25 GB atau > 25K ops/s)
- [ ] Optimize slow query:
SLOWLOG GET 100, refactor pipeline - [ ] Audit security: requirepass, bind address, TLS untuk remote access
- [ ] Setup alerting: memory > 80%, replication lag > 10s, ops/s spike
- [ ] Document runbook: 3 insiden paling mungkin + recovery steps
Horizon 4: Hari 76-90 (Production-Hardened)
- [ ] Stress test: 10x volume ekspektasi normal
- [ ] Backup restore test bulanan (jangan backup tanpa test restore!)
- [ ] Review retention policy (RDB berapa lama disimpan, AOF compaction)
- [ ] Update aplikasi untuk handle failover gracefully (retry, circuit breaker)
- [ ] Plan disaster recovery: cross-region backup, documented procedure
7 Trends 2026-2027 yang Akan Mengubah Landscape
- Redis 8.0 dengan vector sets native — AI/RAG workload langsung di Redis, tanpa module tambahan.
- Redis Flex (disk-backed) — untuk dataset > RAM, harga turun 5-10x untuk workload tertentu.
- Active-Active CRDT — Redis Enterprise punya geo-replication conflict-free, game changer untuk global app.
- Multi-modal Redis Stack — JSON + Search + TimeSeries + Vector dalam satu deployment, query hybrid.
- Serverless Redis (Upstash, Redis Cloud) — bayar per request, edge-compatible, harga untuk spiky workload.
- Redis sebagai message broker mainstream — Streams menggantikan Kafka untuk use case mid-scale, simpler ops.
- OpenTelemetry support native — distributed tracing built-in, observability stack simplify.
Security Deep-Dive
7 Attack Vector untuk Redis (dan Mitigasi)
- Unauthenticated access dari internet — Redis default tanpa password, port 6379 terbuka = disaster. Fix:
requirepass+bindke internal IP + firewall. - Command injection via
CONFIG SET— attacker bisa ubah config Redis kalau punya akses. Fix: DisableCONFIGcommand viarename-command CONFIG "". - Lua script DoS — script kompleks bisa block event loop. Fix:
lua-time-limit 5000(default), monitor denganSLOWLOG. - Memory exhaustion via massive writes — attacker push data sampai OOM. Fix:
maxmemory+maxmemory-policy+ monitoring alert. - Persistence path traversal — backup file bisa di-overwrite. Fix: Run sebagai non-root, restrict
dirpermission. - Replication MITM — attacker intercept replikasi, inject data. Fix: TLS untuk replikasi +
masterauthstrong password. - AOF rewrite race condition — historical CVE di Redis 5.x. Fix: Update ke Redis 7.4+ (patched).
7 Hardening Commands
# /etc/redis/redis.conf production-hardened
requirepass your-very-strong-password-here
bind 10.0.0.0/8 # restrict ke internal network
protected-mode no # karena sudah ada auth + bind
port 6379
rename-command CONFIG "" # disable CONFIG command
rename-command FLUSHALL "" # disable FLUSHALL (atau pakai ACL untuk permit specific user)
rename-command FLUSHDB ""
aclfile /etc/redis/users.acl # Redis 6+ ACL
# TLS (optional tapi recommended untuk remote access)
tls-port 6380
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key
tls-ca-cert-file /path/to/ca.crt
Kapan Pake Redis (Dan Kapan Jangan)
✅ Pakai Redis kalau:
- Session store (sub-ms vs DB 10-50ms)
- Real-time leaderboard (Sorted Set + ZINCRBY)
- Rate limiter (atomic
INCR+EXPIRE) - Job queue (List + BLPOP, atau Stream + consumer group)
- Pub/Sub atau Streams untuk real-time
- Distributed locks (
SET key val NX EX 30) - Distributed counters (
INCR) - Cache dengan TTL
- AI/RAG vector search (Redis Stack)
- Metrics / time series (RedisTimeSeries)
- AI/RAG dengan Vector Sets (Redis 8.0) — alternative Pinecone
- Geo-spatial query (built-in GEO commands)
- Bloom filter untuk duplicate detection
- Idempotency token untuk exactly-once API
❌ Jangan pakai Redis kalau:
- Primary database tanpa persistence
- Butuh complex query (no JOIN, no WHERE) → pake SQL
- Dataset > memori yang tersedia (atau pakai Redis Flex disk-backed)
- Strong consistency across multiple ops → transactional DB
- Long-term archival (gak durable by default tanpa backup strategy)
- ACID transactions → PostgreSQL/MySQL
- Heavy aggregations/analytics → OLAP DB (ClickHouse, BigQuery)
- Multi-threaded CPU-bound workload (Redis single-threaded by design)
Redis vs Memcached (Head-to-Head)
| Pilih Redis kalau | Pilih Memcached kalau |
|---|---|
| Butuh data structures (Hash, Set, Sorted Set) | Pure string LRU cache |
| Butuh persistence (RDB/AOF) | Existing Memcached expertise |
| Butuh Streams atau Pub/Sub | Extreme memory efficiency di scale |
| Butuh replication | Multi-threaded simple cache |
| Lebih dari simple KV | Cloudflare Workers KV layer |
| Butuh vector search (AI/RAG) | |
| Butuh geo-spatial (GEO commands) | |
| Butuh distributed lock (Redlock) |
Command Quick Reference (Diperluas)
# Strings / Counters
SET key value EX 60 # set dengan TTL
INCR counter # atomic increment
INCRBY counter 10 # increment by 10
EXPIRE counter 3600 # set TTL
SET key val NX EX 30 # set kalau belum ada (distributed lock)
SET key val XX EX 30 # set kalau sudah ada
# Lists (queues)
LPUSH queue task # add ke head
RPUSH queue task # add ke tail
LPOP queue / RPOP queue # pop dari head/tail
BLPOP queue 0 # blocking pop (0 = forever)
LMOVE src dst LEFT RIGHT # atomic move
LTRIM queue 0 9999 # keep hanya 10K terakhir
# Sorted Sets (leaderboards + rate limiters)
ZADD lb 100 player1
ZINCRBY lb 5 player1
ZREVRANGE lb 0 9 WITHSCORES # top 10
ZRANGEBYSCORE lb 100 200 # range by score
ZREMRANGEBYSCORE lb 0 1690123456789 # hapus entry lama
# Hashes (sessions + objects)
HSET user:1 name "Adi" age 30
HINCRBY user:1 visits 1
HGETALL user:1
HDEL user:1 field
HEXPIRE user:1 600 field # TTL per field (Redis 7.4+)
HTTL user:1 field # cek TTL field
# Sets
SADD tags:article:42 redis database
SISMEMBER tags:article:42 redis
SINTER tags:user:1 tags:user:2
SUNIONSTORE popular tags:user:*
# Streams
XADD events * type "click" user 1
XREADGROUP GROUP workers w1 COUNT 10 STREAMS jobs >
XACK jobs workers 1690123456789-0
XRANGE events - + COUNT 10
XLEN events
XDEL events 1690123456789-0
# Pub/Sub
PUBLISH channel "message"
SUBSCRIBE channel
PSUBSCRIBE news.* # pattern subscribe
# GEO (Redis 3.2+)
GEOADD locations 106.8456 -6.2088 "jakarta"
GEODIST locations jakarta yogyakarta km
GEORADIUS locations 107 6 50 km WITHDIST COUNT 5
# HyperLogLog
PFADD visitors:2026-07-31 user1 user2 user3
PFCOUNT visitors:2026-07-31 # estimate unique
# Bitmap
SETBIT user:active:2026-07-31 42 1 # user 42 active hari ini
BITCOUNT user:active:2026-07-31 # DAU
# Vector Sets (Redis 8.0+)
VADD embeddings <vec> "doc:42"
VSIM embeddings <query_vec> COUNT 10
VREM embeddings "doc:42"
VINFO embeddings
VEMB embeddings "doc:42"
# Bloom Filter (module)
BF.RESERVE bloom:seen 0.01 1000000
BF.ADD bloom:seen "user:42"
BF.EXISTS bloom:seen "user:42"
# TimeSeries (module)
TS.CREATE sensor:1 RETENTION 86400000
TS.ADD sensor:1 * 28.5
TS.RANGE sensor:1 - + AGGREGATION avg 60000
# Search (module)
FT.CREATE idx ON HASH SCHEMA title TEXT body TEXT
FT.SEARCH idx "query" LIMIT 0 10
# JSON (module)
JSON.SET user:1 . '{"name":"Adi","age":30}'
JSON.GET user:1 .name
JSON.NUMINCRBY user:1 .age 1
# Lua scripting
EVAL "return redis.call('GET', KEYS[1])" 1 key
EVALSHA <sha> 1 key
# Scans (JANGAN pakai KEYS di production)
SCAN 0 MATCH user:* COUNT 100
# Diagnostics
INFO memory
INFO replication
INFO stats
INFO commandstats
INFO keyspace
SLOWLOG GET 10
SLOWLOG LEN
SLOWLOG RESET
CLIENT LIST
DBSIZE
MEMORY DOCTOR
MEMORY USAGE key
MEMORY STATS
--bigkeys
--hotkeys (Redis 7.0+)
--latency
--latency-history
30 FAQ 6 Kategori
Dasar (6)
1. Redis itu cache atau database? Data structure server in-memory. Bisa jadi cache (dengan TTL) atau primary DB (dengan RDB+AOF), tapi lebih optimal sebagai cache + struktur data.
2. Bedanya Redis sama Memcached? Redis punya 8+ tipe data, persistence, replication. Memcached pure string LRU, multi-threaded, simpler.
3. Redis single-threaded bener? Command execution single-threaded (event loop). I/O bisa multi-threaded (Redis 8.0+).
4. Maksimum memory Redis? Tergantung OS. Redis 64-bit sampai 1 TB tested. Production realistic 256 GB per node.
5. Redis bisa di-restart tanpa data loss? Ya, kalau RDB atau AOF enabled. Default config save RDB setiap beberapa menit.
6. Redis license? Apa yang berubah 2024? Redis 7.4 BSD. Redis 8.0+ RSAL/SSPL (source-available, bukan OSI-approved). Untuk license-friendly, pakai Valkey (Linux Foundation).
Setup (4)
7. Redis install di mana untuk production? Self-hosted: Hetzner, Contabo, DO, AWS EC2. Managed: Upstash, ElastiCache, Redis Cloud, Redis Enterprise.
8. Minimal RAM untuk Redis production? 1 GB (small) sampai 64+ GB (enterprise). Rule of thumb: 1.5x dataset peak.
9. Sentinel atau Cluster? Sentinel: 1 master + N replica, HA, simple. Cluster: 3+ master + 3+ replica, sharding, scale out.
10. Redis di Docker production-ready? Ya, dengan persistent volume, network host atau proper bridge, dan restart policy.
Performance (5)
11. Kenapa Redis lambat?
Biasanya: (1) big keys, (2) KEYS di production, (3) pipeline kurang, (4) eviction storm, (5) Lua script blocking.
12. Cara optimize Redis? Pipeline, Lua untuk atomic, SCAN bukan KEYS, hash untuk object, sorted set untuk leaderboard.
13. Throughput maksimum Redis? Standard 100K ops/s per instance (single-threaded). Multi-threaded I/O (8.0) 300-500K. DragonflyDB 1M+.
14. Latency tipikal Redis? Sub-millisecond untuk simple command (GET/SET/INCR). 1-5 ms untuk complex (ZADD, HGETALL besar, Lua).
15. Pipelining berapa banyak ideal? 50-100 commands per pipeline. Lebih besar dari itu diminishing return.
Operations (5)
16. Cara backup Redis? RDB snapshot (BGSAVE) + copy ke S3. Schedule daily. Wajib test restore!
17. Cara monitor Redis? Prometheus + redis_exporter + Grafana. Alert: memory > 80%, replication lag > 30s, ops/s spike.
18. Cara failover manual?
SENTINEL FAILOVER mymaster (Sentinel) atau CLUSTER FAILOVER (Cluster).
19. Cara migrate dari Redis 6 ke 8?
Backup → upgrade binary → restart → verify INFO server (cek redis_version). Major upgrade test di staging dulu.
20. Cara debug slow query?
SLOWLOG GET 10 → analisis command yang lambat → optimize (pipeline, Lua, atau re-model data).
Comparison (5)
21. Redis vs PostgreSQL untuk session? Redis 0.5-2ms, PostgreSQL 10-50ms. Redis lebih cepat, tapi PostgreSQL persistent by default.
22. Redis vs MongoDB? Redis untuk hot data (session, cache, real-time). MongoDB untuk document storage dengan query.
23. Redis vs Kafka untuk message broker? Redis Streams cocok untuk mid-scale (1-10K msg/s). Kafka untuk high-throughput (100K+ msg/s) dengan replay.
24. Redis vs RabbitMQ? Redis lebih simple, embedded. RabbitMQ lebih feature-rich (routing, ack, dead letter).
25. Redis 8.0 vs Redis 7.4 untuk production baru? Redis 8.0 (Vector Sets + multi-thread I/O + AOF multi-part) worth the upgrade untuk new project. Untuk existing, evaluate per use case.
Karir (5)
26. Belajar Redis dari mana?
- Redis University (gratis, official)
- Redis documentation
- Redis source code (10K lines, readable C)
- Real project: setup cluster, load test, optimize
27. Redis interview question?
- "Apa itu event loop single-threaded? Kenapa bukan multi-threaded?"
- "Jelaskan RDB vs AOF."
- "Bagaimana cara implement distributed lock yang benar?"
- "Cara handle hot key di Redis cluster?"
28. Career path Redis specialist?
- Junior: install + basic ops + monitor
- Mid: tuning + cluster + Lua scripting
- Senior: arsitektur + multi-region + observability + compliance
- Principal: cost optimization + innovation + team leadership
29. Salary range Indonesia 2026?
- Junior: Rp 8-15 jt/bulan
- Mid: Rp 18-35 jt/bulan
- Senior: Rp 40-80 jt/bulan
- Principal: Rp 100+ jt/bulan
30. Redis certification?
- Redis Certified Developer (RCD) — official
- AWS Database Specialty (covers ElastiCache)
- CKA (untuk Kubernetes Redis operator)
Cheat Sheet 5 Menit
───────────────────────────────────────────────────────┐
│ REDIS PRODUCTION CHEAT SHEET │
├─────────────────────────────────────────────────────┤
│ SETUP: docker run -d --name redis -p 6379:6379 \ │
│ -v /data/redis:/data redis:7.4-alpine │
│ │
│ BASIC: │
│ SET key value EX 60 # cache + TTL │
│ GET key # read │
│ INCR counter # atomic counter │
│ DEL key # delete │
│ EXISTS key # check │
│ EXPIRE key 60 # set TTL │
│ │
│ STRUCTURES: │
│ HSET user:1 name "Adi" # hash │
│ LPUSH queue task # list/queue │
│ SADD tags redis db # set │
│ ZADD lb 100 player1 # sorted set │
│ XADD events * type click # stream │
│ │
│ ATOMIC LOCK: │
│ SET lock:res token NX EX 30 # acquire │
│ DEL lock:res # release (verify token via Lua) │
│ │
│ ANTI-PATTERNS (JANGAN!): │
│ ❌ KEYS * di production (pakai SCAN) │
│ ❌ Cache key tanpa TTL │
│ ❌ Redis as primary DB tanpa backup │
│ ❌ Single instance untuk production │
│ ❌ 1 replica (split-brain risk) │
│ │
│ MONITOR: │
│ INFO memory # memory usage │
│ INFO stats # ops/s │
│ SLOWLOG GET 10 # slow queries │
│ CLIENT LIST # connections │
│ │
│ BACKUP: │
│ redis-cli BGSAVE # snapshot │
│ cp /data/dump.rdb /backup/ # copy │
│ ⚠️ TEST RESTORE BULANAN! │
└─────────────────────────────────────────────────────┘
Hard Rules untuk Production (Recap)
Ini non-negotiable. Diambil dari anti-patterns + persistence guide:
- Selalu set TTL di cache key.
SET key value EX <seconds>. No exceptions. - JANGAN pakai
KEYSdi production. PakaiSCANatau Redis Search. - Jangan jalankan ephemeral Redis sebagai primary DB tanpa persistence. Enable RDB atau AOF.
- Hindari hot keys. Distribute atau replicate kalau single key dapat > 10K ops/s.
- Untuk job queue yang butuh durability, pakai Streams, bukan List+BLPOP.
- Untuk multi-key ops di cluster, pakai hash tags
{...}untuk colocate. - Di open-source cluster, pakai 2 replicas per master (odd quorum).
- Kalau dataset > 25GB atau ops > 25K/sec, shard.
- Monitor dengan
INFO+SLOWLOG+ alerting. Jangan deploy tanpa observability. - Backup + test restore. Backup tanpa test restore = wishful thinking.
Rekomendasi Akhir
Untuk 90% use case:
- Baru mulai, volume kecil-menengah → Single instance + RDB 5 menit, AOF setiap detik
- 10-50K ops/s, dataset 1-10 GB → Master-replica 2 replica + Sentinel
- 50K+ ops/s atau > 25 GB → Redis Cluster minimal 3 master + 3 replica
- Butuh zero-downtime migrasi → Redis Enterprise atau AWS ElastiCache dengan multi-AZ
Anti-rekomendasi:
- Jangan pakai Redis sebagai primary database tanpa RDB+AOF aktif
- Jangan pakai
KEYSdi production, kapanpun, apapun alasannya - Jangan deploy tanpa monitoring — outage jam 2 pagi tanpa telemetry = nightmare
- Jangan skip backup — VPS bisa crash, snapshot bisa corrupt
Resources (90+ tools, libraries, services)
Official & Documentation
- Redis Official Documentation
- Redis University — free courses
- Redis Blog
- Redis GitHub — source code
- Redis Insight — GUI client
- Redis CLI Reference
- Redis 7.4 Release Notes
- Redis 8.0 Preview
Client Libraries
- redis-py (Python)
- ioredis (Node.js)
- node-redis (Node.js official)
- go-redis (Go)
- Jedis (Java)
- Lettuce (Java, reactive)
- Redisson (Java, distributed)
- StackExchange.Redis (.NET)
- redis-rs (Rust)
- hiredis (C)
Monitoring & Observability
- redis_exporter (Prometheus)
- Grafana Redis Dashboard
- Redis Exporter for Datadog
- New Relic Redis Integration
- Datadog Redis Dashboard
- Redis Insight Profiler
Modules
- RedisJSON
- RediSearch
- RedisTimeSeries
- RedisBloom
- RedisGraph
- RedisGears
- RedisAI
- Vector Sets (Redis 8.0+)
Alternative / Replacement
- KeyDB
- DragonflyDB
- Valkey
- Garnet (Microsoft)
- Apache Kvrocks
- Redka — Go re-implementation
Managed Services
- Redis Cloud
- AWS ElastiCache for Redis
- Upstash Redis
- Azure Cache for Redis
- Google Cloud Memorystore
- Aiven for Redis
- DigitalOcean Managed Redis
- Render Redis
Tools
- RedisBloom CLI
- redis-tools (RDB tools)
- redis-dump
- redis-cli (official)
- Redis GUI: Medis (macOS)
- Redis GUI: AnotherRedisDesktopManager
- Redis GUI: RedisDesktopManager
- Redis CLI: redis-cli-docker
- Redis Cluster CLI: redis-cli --cluster
Kubernetes Operators
- Redis Operator (Spotahome)
- Redis Operator (OT-CONTAINER-KIT)
- KubeDB (Redis)
- Bitnami Redis Helm Chart
Testing
Lua Scripting
Distributed Lock
Pub/Sub & Streams
Security
Books
- Redis in Action (Josiah Carlson)
- Redis Essentials (Maxwell Dayvson da Silva)
- Mastering Redis (Jeremy Nelson)
- Redis 8.0 Cookbook (2026)
Communities
Indonesian Resources
- Petani Kode — Redis Tutorial Indonesia
- CodePolitan — Redis Course
- BuildWithAngga — Redis Indonesia
- Indonesia Redis Community (Telegram)
Webinars & Talks
Referensi (110+ sources, 13 categories)
Documentation & Specs (12)
- Redis Official Documentation
- Redis Anti-Patterns Guide (Ajeet Raina, 2026-02-25)
- Redis Persistence Guide
- Redis Cluster Specification
- Redis Streams Introduction
- Redis Pub/Sub Documentation
- Redis ACL (Access Control List)
- Redis Security Guide
- Redis SLOWLOG Documentation
- Redis 7.4 Release Notes
- Redis 8.0 Preview (Vector Sets)
- Redis Stack Documentation
Pricing & Services (10)
- Upstash Pricing
- AWS ElastiCache for Redis Pricing
- Redis Enterprise Pricing
- Hetzner Cloud Pricing
- Contabo VPS Pricing
- DigitalOcean Managed Redis Pricing
- Azure Cache for Redis Pricing
- Google Memorystore Pricing
- Aiven Redis Pricing
- Render Redis Pricing
Benchmarks & Performance (8)
- AWS Builders Library — Time Series Databases
- Memcached vs Redis Benchmark (AWS)
- DragonflyDB Benchmark
- KeyDB Benchmark
- Valkey vs Redis Benchmark
- Garnet Benchmark (Microsoft Research)
- Pinecone vs Redis Vector Search
- Redis Stack Vector Search Performance
Module Documentation (10)
- RedisJSON Commands
- RediSearch Commands
- RedisTimeSeries Commands
- RedisBloom Commands
- RedisGears Tutorial
- Vector Sets Commands (Redis 8.0)
- Redis Graph Documentation
- RedisSQL (SQL on Redis)
- RedisTimeSeries Aggregation
- Bloom Filter Tutorial
Comparison & Alternatives (12)
- Redis vs Memcached (official)
- Redis vs KeyDB (Snap)
- Redis vs DragonflyDB
- Redis vs Valkey (Linux Foundation)
- Garnet vs Redis (Microsoft Research)
- Redis vs Cassandra (use cases)
- Redis vs MongoDB (use cases)
- Redis vs DynamoDB
- Redis vs Hazelcast (in-memory data grid)
- Redis vs Apache Geode
- Redis vs Coherence (Oracle)
- Redis vs GridGain
Patterns & Best Practices (12)
- Redlock Algorithm (official)
- Rate Limiting Pattern (Redis University)
- Idempotency Token Pattern
- Session Management Pattern
- Geo-spatial Pattern (Uber H3 + Redis)
- Leaderboard Anti-Cheat Pattern
- Bloom Filter Pattern
- Cache Aside Pattern (Microsoft Azure)
- Write Behind Pattern
- Pub/Sub vs Streams (official)
- Redis Lua Scripting Best Practices
- Hot Key Detection Pattern
Anti-Patterns (8)
- Redis Anti-Patterns (Redis University)
- Cache Anti-Patterns (AWS Builders Library)
- Common Redis Mistakes (Medium)
- Redis Security Vulnerabilities (CVE Database)
- Redis Lua Script DoS Prevention
- Redis Memory Fragmentation
- Redis Replication Pitfalls
- Redis Cluster Mistakes
Security (8)
- OWASP Redis Security
- Redis CVE Database
- Redis ACL Tutorial
- Redis TLS Setup Guide
- HashiCorp Vault Redis Database Plugin
- PCI DSS Compliance for Redis
- GDPR Compliance for Data Storage
- UU PDP Indonesia (UU No. 27 Tahun 2022)
Indonesian Context (8)
- @stokquproject TikTok Slides (verified via analyze_image 2026-07-24)
- Tokopedia Engineering Blog
- Gojek Engineering Blog
- Bukalapak Engineering Blog
- Kredivo Engineering Blog
- Telkomsel Developer Portal
- Indonesia Redis Community (Telegram)
- Indonesia Backend Developer Community
Case Studies (8)
- Twitter Redis Case Study
- GitHub Redis Case Study
- Pinterest Redis Case Study
- Snapchat Redis (KeyDB) Case Study
- Stack Overflow Redis
- GitLab Redis High Availability
- Craigslist Redis Use Case
- Discourse Redis Use Case
Books & Papers (8)
- Redis in Action (Manning)
- Designing Data-Intensive Applications (Martin Kleppmann)
- Distributed Systems: Concepts and Design (Coulouris)
- Database Internals (Alex Petrov)
- The Morning Paper — Adrian Colyer
- ACM Queue — Distributed Systems
- IEEE Transactions on Parallel and Distributed Systems
- VLDB Conference Proceedings
Standards & Compliance (8)
- PCI DSS 4.0 Standard
- GDPR Full Text
- UU PDP Indonesia (UU No. 27 Tahun 2022)
- HIPAA Security Rule
- ISO/IEC 27001 Standard
- SOC 2 Compliance
- NIST Cybersecurity Framework
- CIS Benchmarks — Redis
News & Updates (8)
- Redis Blog
- Redis Newsletter
- InfoQ Redis
- Hacker News Redis
- Reddit r/redis
- The New Stack — Redis
- DZone Redis
- Database Trends & Applications
Tools & Utilities (8)
- redis-rdb-tools
- redis-dump
- AnotherRedisDesktopManager
- Medis (macOS GUI)
- RedisBloom CLI
- memtier_benchmark
- redis-cli Reference
- Spotahome Redis Operator
Observability (6)
- Prometheus Redis Exporter
- Grafana Redis Dashboard 11835
- OpenTelemetry Redis Instrumentation
- Datadog Redis Monitoring
- New Relic Redis
- Redis Insight Profiler
Books & Tutorials (Indonesian) (6)
- Ebook Redis Bahasa Indonesia (Petani Kode)
- Tutorial Redis CodePolitan
- Belajar Redis untuk Pemula (Duniailkom)
- Redis Tutorial BuildWithAngga
- Sanbercode Redis Course
- Dicoding Redis
Selamat ngoprek — dan ingat, Redis itu powerful kalau lo paham data structure-nya. Tapi 90% tim developer cuma pakenya sebagai cache, terus bingung kenapa Redis mereka kena masalah "memory penuh" atau "CPU 100% di tengah malam" — biasanya karena anti-pattern 1, 2, atau 3.
Mulai dengan: set TTL di setiap cache key, ganti KEYS dengan SCAN, dan monitor INFO memory mingguan. Itu sudah nutup 80% common bugs. 🦀
Resources Pendukung — Temen Lo Buat Redis Production Anti-Pattern
Redis itu 30% config, 70% operational discipline. Salah set maxmemory policy = data loss diam-diam. Salah pilih eviction = cache miss naik ke 60%. Salah index structure = query O(N) di production. Tools di bawah yang udah lo-judge reasonable buat Redis production, bukan Redis-as-hobby.
Sambil menyelam minum air #1 — free compute buat benchmark tipe data: Sebelum lo commit ke Redis Stack (dengan RedisJSON, RediSearch, RedisGraph), lo butuh tau workload lo butuh module-nya atau cukup core Redis. Alibaba Cloud free tier kasih lo ECS instance gratis 30 hari — cukup buat benchmark 8 tipe data Redis (string, hash, list, set, zset, stream, bitmap, hyperloglog) di realistic workload, ukur memory usage + operation latency. Kalo lo install semua module tanpa benchmark, memory overhead bisa 3-5x.
Sambil menyelam minum air #2 — managed Redis (Tair) production-grade: Self-host Redis = persistence config (RDB vs AOF), replication, sentinel vs cluster, backup retention. Satu config salah = data loss. Pakai Alibaba Cloud managed Redis Tair — automated backup, AOF persistence, cluster mode built-in, monitoring alert, 99.99% SLA. Lo fokus ke logic app, Redis ops handled. Worth it kalo data lo > 10GB atau concurrent > 5K req/s.
Sambil menyelam minum air #3 — managed PostgreSQL buat relational cache miss: Anti-pattern #1 Redis = dipake sebagai primary database tanpa ACID. Kalo lo butuh relational integrity, PostgreSQL wajib sebagai system of record. Alibaba Cloud managed RDS PostgreSQL kasih point-in-time recovery, automated backup. Pakai Redis sebagai cache, PostgreSQL sebagai source of truth — gak ada lagi "Redis down = data hilang".
Sambil menyelam minum air #4 — free compute buat load test anti-pattern: Anti-pattern Redis gak keliatan di dev, baru kerasa di production traffic. Alibaba Cloud free tier credits bisa cover 2-3 instance untuk distributed load test (memtier_benchmark, redis-benchmark) — simulasi realistic 10K-50K req/s ke Redis lo, ukur di mana bottleneck muncul. Kalo lo cuma test di localhost, anti-pattern cache stampede gak akan ke-expose.
Sambil menyelam minum air #5 — observability buat Redis monitoring: Anti-pattern #5 = gak monitor memory usage, eviction rate, connection count. Tanpa monitoring = Redis diam-diam swap ke disk, latency spike ke 5 detik. Alibaba Cloud ARMS / CloudMonitor integrate ke Redis INFO command, kasih lo dashboard per-instance dengan alert custom. Set alert kalo
used_memory > 80% maxmemory= early warning sebelum OOM.
Sambil menyelam minum air #6 — WAF + DDoS buat Redis public endpoint: Anti-pattern #6 = expose Redis ke public tanpa auth. Default Redis 6379 tanpa password = world-readable. Satu bot scan port 6379 = data exfiltration. Alibaba Cloud Web Application Firewall + Security Group kasih whitelist IP, rate limit per-source, anomaly detection. Defense-in-depth kalo Redis lo jadi bagian dari API stack.
Sambil menyelam minum air #7 — object storage buat AOF + RDB backup: Anti-pattern #7 = backup Redis di local disk, gak ada offsite copy. Disk VPS corrupt = data hilang. Pakai Alibaba Cloud OSS — scheduled backup ke bucket dengan versioning enabled, point-in-time recovery. Combine dengan managed Redis = double layer backup redundancy. Worth it kalo data lo mission-critical.
Sambil menyelam minum air #8 — Qwen buat analyze Redis slow log: Slow log Redis = indicator anti-pattern. Tapi baca 10K lines slow log manual = buang-buang waktu. Pakai Alibaba Cloud Qwen3-Max via PAI — kirim slow log ke Qwen, minta pattern analysis + recommendation. Qwen bisa detect key clustering, command pattern, suggestion index structure. Otomatis, gak perlu lo pusing baca log manual.
Sambil menyelam minum air #9 — CDN buat static content + Redis hybrid: Anti-pattern #8 = pake Redis untuk static content (image, CSS, JS) yang gak perlu invalidate. Hybrid: Redis untuk dynamic data (session, cart, ranking), CDN untuk static. Pakai Alibaba Cloud CDN — cache static di edge, kurangi Redis memory pressure 40-60%. Lo tetep punya Redis untuk data yang butuh invalidation, sisanya handled CDN.
Sambil menyelam minum air #10 — opsi managed tambahan: Kalau lo pengen bandingin langsung sama konteks Skenario B: Production Self-Hosted Master-Replica (30-60 menit) di atas, ECS 9th-gen g9i Alibaba Cloud nyediain jalur managed yang bisa lo tes tanpa kelola infra sendiri.
Kalo lo butuh Redis production tuning spesifik (memory optimization, persistence strategy, cluster sizing), drop comment — gue bisa bantu breakdown cost vs performance tradeoff buat workload lo.
Mulai dengan: set TTL di setiap cache key, ganti KEYS dengan SCAN, dan monitor INFO memory mingguan. Itu sudah nutup 80% common bugs. 🦀
Topik Terkait
Artikel lain yang relevan dengan topik AI agent, workflow, dan teknis toolkuy:
💬 Komentar (0)
Belum ada komentar. Jadilah yang pertama! 💬