Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Redis Hacks
Search
David Cramer
May 03, 2014
Technology
3
220
Redis Hacks
Python Nordeste 2014 - Lightning Talk
David Cramer
May 03, 2014
Tweet
Share
More Decks by David Cramer
See All by David Cramer
Mastering Duct Tape (PyCon Balkan 2018)
zeeg
2
870
Open Source as a Business (PyCon SG 2014)
zeeg
0
340
Angular.js Workshop (PyCon SG 2014)
zeeg
0
230
Architecting a Culture of Quality
zeeg
2
320
Release Faster
zeeg
12
1.3k
Open Source as a Business (EuroPython 2013)
zeeg
18
17k
Building to Scale (PyCon TW 2013)
zeeg
18
1.3k
Building to Scale
zeeg
28
24k
Lessons in Testing - DjangoCon 2012
zeeg
8
1.4k
Other Decks in Technology
See All in Technology
システム・ML活用を広げるdbtのデータモデリング / Expanding System & ML Use with dbt Modeling
i125
1
300
偏光画像処理ライブラリを作った話
elerac
1
150
設計を積み重ねてシステムを刷新する
sansantech
PRO
0
130
日経のデータベース事業とElasticsearch
hinatades
PRO
0
180
AI Agent時代なのでAWSのLLMs.txtが欲しい!
watany
2
140
大規模アジャイルフレームワークから学ぶエンジニアマネジメントの本質
staka121
PRO
2
120
Exadata Database Service on Cloud@Customer セキュリティ、ネットワーク、および管理について
oracle4engineer
PRO
2
1.5k
スキルだけでは満たせない、 “組織全体に”なじむオンボーディング/Onboarding that fits “throughout the organization” and cannot be satisfied by skills alone
bitkey
0
110
PHPカンファレンス名古屋-テックリードの経験から学んだ設計の教訓
hayatokudou
2
530
脳波を用いた嗜好マッチングシステム
hokkey621
0
260
プロダクトエンジニア 360°フィードバックを実施した話
hacomono
PRO
0
130
エンジニアの育成を支える爆速フィードバック文化
sansantech
PRO
3
1.2k
Featured
See All Featured
[RailsConf 2023] Rails as a piece of cake
palkan
53
5.3k
Agile that works and the tools we love
rasmusluckow
328
21k
Fontdeck: Realign not Redesign
paulrobertlloyd
83
5.4k
How STYLIGHT went responsive
nonsquared
98
5.4k
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
4
360
Building an army of robots
kneath
303
45k
No one is an island. Learnings from fostering a developers community.
thoeni
21
3.1k
YesSQL, Process and Tooling at Scale
rocio
172
14k
Why You Should Never Use an ORM
jnunemaker
PRO
55
9.2k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
33
2.8k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
32
2.1k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
100
18k
Transcript
David Cramer twitter.com/zeeg Redis Hacks (or “How Sentry Scales”)
Buffering Writes
r = Redis() ! def incr(type, id): key = 'pending:{}'.format(type)
! r.zincrby(key, id, 1)
r = Redis() ! def flush(type): key = 'pending:{}'.format(type) result
= r.zrange(key, 0, -1, withscores=True) ! for id, count in result: prms = {'type': type, 'count': count, 'id': id} ! sql(""" update %(type)s set count = count + % (count)d where id = %(id)s """, prms)
Rate Limiting
r = Redis() ! def process_hit(project_id): epoch = time() /
60 key = ‘{}:{}’.format(project_id, epoch) ! pipe = r.pipeline() pipe.incr(key) pipe.expire(key, 60) result = pipe.execute() ! # return current value return int(result[0])
def request(project_id): result = process_hit(project_id) if result > 20: return
Response(status=429) return Response(status=200)
Time Series Data
def count_hits_today(project_id): start = time() end = now + DAY_SECONDS
! pipe = r.pipeline() for epoch in xrange(now, end, 10): key = ‘{}:{}’.format( project_id, epoch) pipe.get(key) results = pipe.execute() ! # remove non-zero results results = filter(bool, results) # coerce remainder to ints results = map(int, results) # return sum of buckets return sum(results)
Good-enough Locks
from contextlib import contextmanager ! r = Redis() ! @contextmanager
def lock(key, nowait=True): while not r.setnx(key, '1'): if nowait: raise Locked('try again soon!') sleep(0.01) ! # limit lock time to 10 seconds r.expire(key, 10) ! # do something crazy yield ! # explicitly unlock r.delete(key)
def do_something_crazy(): with lock('crazy'): print 'Hello World!'
Basic Sharding via Nydus
from nydus.db import create_cluster ! redis = create_cluster({ 'backend': 'nydus.db.backends.redis.Redis',
'hosts': { 0: {'db': 0}, 1: {'db': 1}, }, 'router': 'nydus.db.routers.keyvalue.PartitionRouter', })
def count_hits_today(project_id): start = time() end = now + DAY_SECONDS
! keys = [] for epoch in xrange(now, end, 10): key = '{}:{}'.format(project_id, epoch) keys.append(key) ! with redis.map() as conn: results = map(conn.get, keys) ! # remove non-zero results results = filter(bool, results) # coerce remainder to ints results = map(int, results) # return sum of buckets return sum(results)