Databases · Intermediate · 24 min
Throttle login attempts with a sliding window in Redis
By Padding · Updated 18 Nov 2026
redis:8 image (Debian) · Redis 8.12 · Python 3.15 · redis-py 8.2 · pytest 9.2
You will protect a Python login function from password guessing with a sliding-window log in Redis sorted sets, checked atomically in a Lua script, with per-address lockouts that double each time, an account-wide rule that asks for an extra check instead of locking the owner out, and tests that replay 50 guesses.
On this page
A login form that accepts unlimited attempts lets anyone guess passwords as fast as your server answers. Firewall tools such as fail2ban block an address after repeated failures, but they only see addresses. Your application also knows which account each guess targets, so it can slow down an attack on one account without punishing everyone behind the same address.
In this tutorial you build that throttle in Redis for a small Python login function. You start with a fixed-window counter and watch it let through twice its limit at a minute boundary. You replace it with a sliding-window log in a sorted set, first with MULTI and then as a Lua script that checks and records an attempt in one atomic step. The finished gate tracks three things: attempts per account and address together, per address across all accounts, and per account across all addresses. Only the first one locks, with a lockout that doubles each time, so an attacker cannot lock the real owner out. Tests replay 50 guesses in each attack shape to prove the rules hold.
The code uses Redis 8.12 and redis-py 8.2 on Python 3.15. Valkey accepts the same commands and Lua scripts, so everything here works against it unchanged.
Step 1 · Check Redis and create the project
Confirm that Redis answers on its default port and see which version it runs:
redis-cli ping
redis-cli INFO server | grep redis_versionIf your Redis needs a password, give it to redis-cli through the REDISCLI_AUTH environment variable, typed at a hidden prompt with read -rs REDISCLI_AUTH && export REDISCLI_AUTH, rather than passing -a on the command line. The Python code reads its connection from a REDIS_URL environment variable and falls back to redis://localhost:6379/0, so no address or password lives in the code.
Create the project and add redis-py, plus pytest for the last step. The ranges allow patch releases and nothing newer:
mkdir -p ~/login-throttle-demo
cd ~/login-throttle-demo
uv init --no-package --python 3.15
uv add "redis>=8.2,<8.3"
uv add --dev "pytest>=9.2,<10"The login function needs one demo account. Give it a random password held in an environment variable, so it never appears in the code or your shell history:
export DEMO_PASSWORD="$(uv run python -c 'import secrets; print(secrets.token_urlsafe(12))')"The variable lasts until you close the terminal. Every command that follows runs in ~/login-throttle-demo in the same terminal.
Check it worked
redis-cli ping printed PONG, and the next line showed something like redis_version:8.12.0. Now check the Python side:
uv run python -c "import redis, sys; print(sys.version.split()[0], redis.__version__)"It prints something like 3.15.2 8.2.0.
Step 2 · Count attempts in fixed windows and watch them burst
The simplest limiter is a counter per account per minute: INCR a key named after the current minute, give it an expiry, and refuse once the count passes the limit. Write it with a made-up clock, so the script replays the same ten seconds every time you run it. The ten attempts land one second apart, from 55 seconds past a minute to 4 seconds past the next:
cat > fixed_window.py <<'PY'
import os
import redis
r = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379/0"), decode_responses=True)
LIMIT = 5
WINDOW = 60 # seconds
BASE = 1_800_000_000 # a made-up clock reading that falls on the start of a minute
def attempt(account: str, t: int) -> tuple[bool, int, int]:
window_start = t - t % WINDOW
key = f"demo-login:fixed:{account}:{BASE + window_start}"
with r.pipeline() as pipe:
pipe.incr(key)
pipe.expire(key, WINDOW * 2)
count, _ = pipe.execute()
return count <= LIMIT, count, window_start
for key in r.scan_iter(match="demo-login:fixed:*"):
r.delete(key)
allowed = 0
for t in range(55, 65):
ok, count, start = attempt("amina", t)
allowed += ok
print(f"t={t}s {'allowed' if ok else 'denied'}, attempt {count} in window {start}-{start + WINDOW - 1}s")
print(f"allowed {allowed} of 10 attempts in 10 seconds")
PY
uv run fixed_window.pyA redis-py pipeline wraps its commands in MULTI and EXEC by default, so the INCR and the EXPIRE happen together. The expiry is twice the window so that a key is never deleted while its minute is still current, and old minutes clean themselves up.
The trouble is the boundary. Five attempts at 55 to 59 seconds fill the first window, and the clock then rolls over to a fresh window with a count of zero. An attacker who times guesses around the boundary gets up to twice the limit in a few seconds, and does it again every minute.
Check it worked
Every line says allowed. The first five count 1 to 5 in window 0-59s, the next five count 1 to 5 again in window 60-119s, and the last line is allowed 10 of 10 attempts in 10 seconds: twice the limit inside ten seconds. Within two minutes of running it, list the keys:
redis-cli --scan --pattern 'demo-login:fixed:*'Two keys, one per minute: demo-login:fixed:amina:1800000000 and demo-login:fixed:amina:1800000060.
Step 3 · Keep a sliding log in a sorted set
A sliding-window log stores every attempt with its time and counts only the ones from the last 60 seconds, whatever the clock says. A sorted set fits: each attempt is a member whose score is its time in milliseconds. ZREMRANGEBYSCORE drops members older than the window, ZADD records the new attempt and ZCARD counts what is left.
Members must be unique. ZADD with a member that already exists only updates its score, so two attempts in the same millisecond would count as one. A random suffix avoids that:
cat > sliding_log.py <<'PY'
import os
import uuid
import redis
r = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379/0"), decode_responses=True)
LIMIT = 5
WINDOW_MS = 60_000
BASE_MS = 1_800_000_000_000 # the same made-up clock, in milliseconds
KEY = "demo-login:sliding:amina"
def attempt(t: int) -> tuple[bool, int]:
now = BASE_MS + t * 1000
with r.pipeline(transaction=True) as pipe:
pipe.zremrangebyscore(KEY, "-inf", now - WINDOW_MS)
pipe.zadd(KEY, {f"{now}:{uuid.uuid4().hex}": now})
pipe.zcard(KEY)
pipe.pexpire(KEY, WINDOW_MS)
_, _, count, _ = pipe.execute()
return count <= LIMIT, count
r.delete(KEY)
allowed = 0
for t in range(55, 65):
ok, count = attempt(t)
allowed += ok
print(f"t={t}s {'allowed' if ok else 'denied'}, {count} in the last 60 s")
print(f"allowed {allowed} of 10 attempts in 10 seconds")
ok, count = attempt(116)
print(f"t=116s {'allowed' if ok else 'denied'}, {count} in the last 60 s")
PY
uv run sliding_log.pyThe same ten attempts now stop at five. The key expires one window after the last attempt, so an account that goes quiet costs no memory.
This version still has two flaws, and both come from MULTI. Commands inside MULTI are queued and run together, but none of them can look at another's result, so the ZADD runs whether or not the attempt is allowed. Refused attempts fill the log too. The last line shows the effect: at 116 seconds, 61 seconds after the first attempt, only three allowed attempts are still in the window, yet the five refused ones keep the count at 9 and the attempt is refused again. A client that keeps retrying stays blocked for as long as it retries, and under a flood the set grows by one member per request.
You could read the count first and add only when allowed, guarded with WATCH and retried on conflict, but that is several round trips and a retry loop. A Lua script does the check and the write in one step.
Check it worked
The first five lines say allowed, the next five say denied with counts 6 to 10, the summary reads allowed 5 of 10 attempts in 10 seconds, and the last line is t=116s denied, 9 in the last 60 s. Within a minute, look at the log itself:
redis-cli ZRANGE demo-login:sliding:amina 0 -1 WITHSCORESNine members, each a millisecond time with a random suffix, followed by the same time as its score, from 1800000057000 to 1800000116000.
Step 4 · Write the gate as a Lua script
Redis runs a Lua script as one operation: no other client's command runs between its lines. That lets one script trim the logs, check every rule, and record the attempt only if it passes. It takes five keys for one login attempt:
pair:<account>:<ip>: the sliding log for this account from this address. This is the strict rule, 5 attempts in 15 minutes, and the only one that locks.ip:<ip>: the log for this address across all accounts, 30 in 15 minutes. It catches one address trying a common password on many accounts.acct:<account>: the log for this account across all addresses, 20 in 15 minutes. It catches guesses spread over many addresses. Reaching it asks for an extra check, such as a CAPTCHA or an email link, instead of refusing outright, so the owner can still get in.lock:<account>:<ip>holds the time the lockout ends, andstrikes:<account>:<ip>counts lockouts until 24 hours pass without a new one, so that each one lasts twice as long as the one before, up to an hour.
cat > gate.lua <<'LUA'
-- KEYS: 1 pair log, 2 ip log, 3 account log, 4 lock, 5 strikes
local now = tonumber(ARGV[1])
local member = ARGV[2]
local window = tonumber(ARGV[3])
local pair_limit = tonumber(ARGV[4])
local ip_limit = tonumber(ARGV[5])
local acct_limit = tonumber(ARGV[6])
local base_lock = tonumber(ARGV[7])
local max_lock = tonumber(ARGV[8])
local strikes_ttl = ARGV[9]
local challenge_ok = ARGV[10] == '1'
-- A lockout for this account from this address wins over everything.
local unlock_at = tonumber(redis.call('GET', KEYS[4]) or '0')
if unlock_at > now then
return {0, 'locked', unlock_at - now}
end
-- Forget attempts that have left the window.
for i = 1, 3 do
redis.call('ZREMRANGEBYSCORE', KEYS[i], '-inf', now - window)
end
-- Milliseconds until the oldest attempt in a log leaves the window.
local function retry_after(key)
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
return tonumber(oldest[2]) + window - now
end
if redis.call('ZCARD', KEYS[2]) >= ip_limit then
return {0, 'ip', retry_after(KEYS[2])}
end
if not challenge_ok and redis.call('ZCARD', KEYS[3]) >= acct_limit then
return {0, 'challenge', retry_after(KEYS[3])}
end
if redis.call('ZCARD', KEYS[1]) >= pair_limit then
local strikes = redis.call('INCR', KEYS[5])
redis.call('PEXPIRE', KEYS[5], strikes_ttl)
local lock_ms = math.floor(math.min(base_lock * 2 ^ (strikes - 1), max_lock))
redis.call('SET', KEYS[4], string.format('%d', now + lock_ms), 'PX', string.format('%d', lock_ms))
redis.call('DEL', KEYS[1])
return {0, 'locked', lock_ms}
end
-- Allowed: record the attempt in all three logs.
for i = 1, 3 do
redis.call('ZADD', KEYS[i], ARGV[1], member)
redis.call('PEXPIRE', KEYS[i], ARGV[3])
end
return {1, 'ok', 0}
LUAA refused attempt returns before the ZADD, so it never enters a log: the flaw from the MULTI version is gone, and each log holds at most its limit. When a lockout starts, the pair log is deleted, so after the lockout the address gets a fresh five attempts, and five more failures earn a lockout twice as long.
The current time comes in as an argument rather than from the server, and the lock stores the time it ends rather than relying only on its expiry. That lets the tests move time forward instantly. The expiries on every key are there for cleanup. If several app servers run this gate and you worry about their clocks drifting apart, a script can read the server clock with redis.call('TIME') instead.
Now the Python wrapper. redis-py's register_script sends the script by its SHA1 hash with EVALSHA and loads it automatically the first time Redis has not seen it:
cat > throttle.py <<'PY'
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
import redis
GATE = (Path(__file__).parent / "gate.lua").read_text()
@dataclass(frozen=True)
class Decision:
allowed: bool
reason: str # ok, locked, ip or challenge
retry_after_ms: int
class LoginThrottle:
def __init__(
self,
client: redis.Redis,
prefix: str,
window_s: int = 900,
pair_limit: int = 5,
ip_limit: int = 30,
account_limit: int = 20,
base_lock_s: int = 60,
max_lock_s: int = 3600,
strikes_ttl_s: int = 86_400,
):
self.client = client
self.prefix = prefix
self.settings = [
window_s * 1000, pair_limit, ip_limit, account_limit,
base_lock_s * 1000, max_lock_s * 1000, strikes_ttl_s * 1000,
]
self.gate = client.register_script(GATE)
def _keys(self, account: str, ip: str) -> list[str]:
p = self.prefix
return [
f"{p}pair:{account}:{ip}",
f"{p}ip:{ip}",
f"{p}acct:{account}",
f"{p}lock:{account}:{ip}",
f"{p}strikes:{account}:{ip}",
]
def attempt(self, account: str, ip: str, now_ms: int | None = None,
challenge_passed: bool = False) -> Decision:
if now_ms is None:
now_ms = int(time.time() * 1000)
member = f"{now_ms}:{uuid.uuid4().hex}"
allowed, reason, retry = self.gate(
keys=self._keys(account, ip),
args=[now_ms, member, *self.settings, 1 if challenge_passed else 0],
)
return Decision(bool(allowed), reason, int(retry))
def succeeded(self, account: str, ip: str) -> None:
pair, _, _, lock, strikes = self._keys(account, ip)
self.client.delete(pair, lock, strikes)
PYsucceeded clears the pair log and strikes after a correct password, so the owner is not punished later for earlier typos. It deliberately leaves the address log alone: otherwise an attacker could log in to an account of their own between guesses and reset their address's count.
Write a short script that makes seven attempts one second apart, against keys of its own:
cat > check_gate.py <<'PY'
import os
import time
import redis
from throttle import LoginThrottle
r = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379/0"), decode_responses=True)
for key in r.scan_iter(match="demo-login:check:*"):
r.delete(key)
gate = LoginThrottle(r, prefix="demo-login:check:")
start = int(time.time() * 1000)
for i in range(7):
print(i + 1, gate.attempt("amina@example.com", "203.0.113.7", now_ms=start + i * 1000))
PY
uv run check_gate.pyCheck it worked
Attempts 1 to 5 print Decision(allowed=True, reason='ok', retry_after_ms=0). Attempt 6 prints Decision(allowed=False, reason='locked', retry_after_ms=60000): the first lockout, 60 seconds. Attempt 7, a second later, is still locked with retry_after_ms=59000. Count the attempts in the account log:
redis-cli ZCARD demo-login:check:acct:amina@example.comIt prints 5: the refused attempts were not recorded.
Step 5 · Put the gate in front of the password check
The gate must run before the password is checked, and every attempt must pass through it, right or wrong. That way 50 guesses sent at once cannot all slip past while the first ones are still being checked: each one is counted the moment it arrives.
The login function below hashes passwords with scrypt from the standard library to keep the demo small. In a real app, use Argon2id (for example with the argon2-cffi library). It also hashes the guess for accounts that do not exist and gives the same answer, so the response does not reveal which email addresses have accounts:
cat > login.py <<'PY'
import hashlib
import hmac
import math
import os
import secrets
import sys
import redis
from throttle import LoginThrottle
SALT = secrets.token_bytes(16)
def hash_password(password: str) -> bytes:
return hashlib.scrypt(password.encode(), salt=SALT, n=2**14, r=8, p=1)
# One demo account. Its password comes from the environment, never from the code.
USERS = {"amina@example.com": hash_password(os.environ["DEMO_PASSWORD"])}
def login(throttle: LoginThrottle, account: str, password: str, ip: str,
now_ms: int | None = None, challenge_passed: bool = False) -> tuple[str, int]:
account = account.strip().lower()
decision = throttle.attempt(account, ip, now_ms=now_ms, challenge_passed=challenge_passed)
if not decision.allowed:
return decision.reason, decision.retry_after_ms
stored = USERS.get(account)
candidate = hash_password(password)
if stored is not None and hmac.compare_digest(stored, candidate):
throttle.succeeded(account, ip)
return "welcome", 0
return "wrong", 0
MESSAGES = {
"welcome": "welcome",
"wrong": "wrong email or password",
"locked": "locked: try again in {seconds} s",
"ip": "too many attempts from this network: try again in {seconds} s",
"challenge": "extra check needed, for example a CAPTCHA or an email link",
}
def main() -> None:
if len(sys.argv) != 3:
sys.exit("usage: login.py ACCOUNT IP, with the password on standard input")
account, ip = sys.argv[1], sys.argv[2]
password = sys.stdin.readline().rstrip("\n")
client = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379/0"), decode_responses=True)
status, retry_ms = login(LoginThrottle(client, prefix="demo-login:"), account, password, ip)
print(MESSAGES[status].format(seconds=math.ceil(retry_ms / 1000)))
if __name__ == "__main__":
main()
PYThe password arrives on standard input rather than as an argument, so it never shows up in the process list. In a web app, ip is the client address your framework gives you. Behind a load balancer or proxy that is the address it forwards, and you should only trust that header from your own proxy. Lower-casing the account first matters: without it, Amina@example.com would get its own fresh set of attempts.
Play the attacker from 203.0.113.7 with six wrong guesses, then log in as the owner from another address, then try the right password from the attacker's address:
for i in 1 2 3 4 5 6; do
echo "guess-$i" | uv run login.py amina@example.com 203.0.113.7
done
printenv DEMO_PASSWORD | uv run login.py amina@example.com 198.51.100.20
printenv DEMO_PASSWORD | uv run login.py amina@example.com 203.0.113.7Check it worked
The first five lines are wrong email or password and the sixth is locked: try again in 60 s. The owner's login from 198.51.100.20 prints welcome, although the account is under attack. The right password from the attacker's address still prints locked: try again in followed by about 60 seconds: during a lockout the password is not even checked, so a lucky guess learns nothing.
Step 6 · Replay 50 guesses with tests
Clicking through attacks by hand is slow, and lockouts take real minutes to expire. The tests below pass now_ms to move time instead, and give each test its own key prefix, which the fixture deletes afterwards, so they never touch the demo keys or each other. Each test sends 50 guesses in a different shape:
- one address against one account, one guess a second
- the same, repeated, to prove each lockout doubles
- one address against one account, then the owner from home
- 50 addresses against one account, as a botnet would
- one address against 50 accounts with one common password (password spraying)
- a few typos followed by the right password, to prove success resets the count
cat > test_login.py <<'PY'
import os
import time
import uuid
import pytest
import redis
from login import login
from throttle import LoginThrottle
PASSWORD = os.environ["DEMO_PASSWORD"]
OWNER = "amina@example.com"
ATTACKER_IP = "203.0.113.7"
OWNER_IP = "198.51.100.20"
@pytest.fixture
def throttle():
client = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://localhost:6379/0"), decode_responses=True)
prefix = f"test:{uuid.uuid4().hex}:"
yield LoginThrottle(client, prefix=prefix)
for key in client.scan_iter(match=prefix + "*"):
client.delete(key)
client.close()
@pytest.fixture
def at():
start = int(time.time() * 1000)
return lambda seconds: start + seconds * 1000
def test_fifty_guesses_from_one_address_check_five_passwords(throttle, at):
results = [login(throttle, OWNER, f"guess-{n}", ATTACKER_IP, now_ms=at(n)) for n in range(50)]
assert [status for status, _ in results[:5]] == ["wrong"] * 5
assert results[5] == ("locked", 60_000)
assert all(status == "locked" for status, _ in results[5:])
def test_each_lockout_lasts_twice_as_long(throttle, at):
locks = []
t = 0
for _ in range(3):
for i in range(5):
assert login(throttle, OWNER, "guess", ATTACKER_IP, now_ms=at(t + i))[0] == "wrong"
status, retry_ms = login(throttle, OWNER, "guess", ATTACKER_IP, now_ms=at(t + 5))
assert status == "locked"
locks.append(retry_ms)
t += 5 + retry_ms // 1000
assert locks == [60_000, 120_000, 240_000]
def test_attacker_cannot_lock_out_the_owner(throttle, at):
for n in range(50):
login(throttle, OWNER, f"guess-{n}", ATTACKER_IP, now_ms=at(n))
assert login(throttle, OWNER, PASSWORD, OWNER_IP, now_ms=at(50)) == ("welcome", 0)
assert login(throttle, OWNER, PASSWORD, ATTACKER_IP, now_ms=at(51))[0] == "locked"
def test_guesses_spread_over_many_addresses_ask_for_a_challenge(throttle, at):
results = [login(throttle, OWNER, f"guess-{n}", f"198.18.0.{n}", now_ms=at(n)) for n in range(50)]
assert sum(status == "wrong" for status, _ in results) == 20
assert results[20][0] == "challenge"
assert login(throttle, OWNER, PASSWORD, OWNER_IP, now_ms=at(50))[0] == "challenge"
assert login(throttle, OWNER, PASSWORD, OWNER_IP, now_ms=at(51), challenge_passed=True) == ("welcome", 0)
def test_one_address_spraying_many_accounts_is_stopped(throttle, at):
results = [login(throttle, f"user{n}@example.com", "Password1", ATTACKER_IP, now_ms=at(n)) for n in range(50)]
assert sum(status == "wrong" for status, _ in results) == 30
assert results[30] == ("ip", 870_000)
def test_a_correct_password_resets_the_count(throttle, at):
for n in range(4):
assert login(throttle, OWNER, "typo", OWNER_IP, now_ms=at(n))[0] == "wrong"
assert login(throttle, OWNER, PASSWORD, OWNER_IP, now_ms=at(4)) == ("welcome", 0)
results = [login(throttle, OWNER, "typo", OWNER_IP, now_ms=at(5 + n))[0] for n in range(6)]
assert results == ["wrong"] * 5 + ["locked"]
PY
uv run pytest -qRead the numbers the tests pin down. From one address, 50 guesses cost the attacker 45 refusals and buy only 5 password checks, and the next round buys 5 more only after a longer wait. Spread across 50 addresses, the account rule stops the guessing after 20, but the owner is asked for one extra check rather than refused. One address trying 50 accounts gets 30 checks, then waits until its oldest attempt leaves the 15-minute window: 870 seconds, since that attempt was made 30 seconds earlier.
Check it worked
pytest ends with 6 passed. Each test runs a few dozen scrypt hashes, so the run takes a few seconds. If a test fails, its message shows the list of results it got, which tells you which rule fired first.
Step 7 · Tune the limits for your users
The numbers in LoginThrottle are starting points. Adjust them with your own traffic in mind before you ship:
- Shared addresses. Many mobile networks, including many in Nigeria and across Africa, share one public IPv4 address among many subscribers with carrier-grade NAT, and offices and universities do the same. A per-address limit of 30 could block a whole campus at 9 a.m. Watch how often the
iprule fires for logins that later succeed, and raise the limit, often into the hundreds, if it fires for real people. - IPv6. One person can hold billions of addresses in a single /64 network, so key the address rules on the /64 prefix, not the full address.
- The extra check. Return the
challengereason to your front end and show a CAPTCHA or send a one-time email link. Keep it light: on a low-end Android phone with prepaid data, a heavy CAPTCHA script costs your user real money, so prefer a small one or an email link. - Messages. Tell people how long to wait, as
login.pydoes, and do not say which rule fired or whether the account exists. - Redis Cluster. A script can only touch keys in one hash slot, and these five keys spread across slots. On a cluster, run the gate once per rule with its own keys, or route all login keys to one node with a hash tag such as
{login}, accepting that one node takes all the load.
You can watch the rules work on your own Redis without changing any code. Count the attempts each log holds for the demo account:
redis-cli ZCARD demo-login:acct:amina@example.com
redis-cli ZCARD demo-login:ip:203.0.113.7Check it worked
Within 15 minutes of the previous step, the account log prints 6: five attempts from the attacker's address and the owner's login from 198.51.100.20 (the locked attempts were never recorded). The address log for 203.0.113.7 prints 5. If you changed a limit, rerun uv run pytest -q: the tests that pin the old numbers fail, which is your reminder to update them along with the code.
Step 8 · Clean up
This deletes every key whose name starts with demo-login: from your Redis database, then the project folder. Check first that nothing of your own uses that prefix:
redis-cli --scan --pattern 'demo-login:*'Then delete the keys and the project:
redis-cli --scan --pattern 'demo-login:*' | xargs -r redis-cli del
cd ~
rm -rf ~/login-throttle-demo
unset DEMO_PASSWORDCheck it worked
redis-cli --scan --pattern 'demo-login:*' | wc -lIt prints 0.
Next steps
- Limit API calls per key with a token bucket, the other common shape of rate limit: /tutorials/rate-limit-an-api-in-application-code.
- Put a coarse per-address limit in front of the whole app at the web server: /tutorials/rate-limit-an-api-with-nginx.
- Add a server-level layer that bans addresses hammering SSH and other services: /tutorials/block-brute-force-logins-with-fail2ban.
- Revisit sorted sets and the other Redis types behind this pattern: /tutorials/learn-redis-data-types-with-redis-cli.
Related tutorials
- Use SQLite safely in a Python app: WAL mode, foreign keys and busy timeoutsYou will build a small room-booking store on SQLite with Python 3.15, reproduce the "database is locked" error with two writer processes, and end with a connection helper that turns on foreign keys, WAL mode, a busy timeout and BEGIN IMMEDIATE writes, plus a tested online backup.
- Run background jobs with Redis Streams and consumer groupsYou will build a small receipt-sending job queue on Redis 8 Streams with two Python workers that share the work, recover jobs from a crashed worker, park repeated failures in a dead-letter stream and never send the same receipt twice.
- Recover the clinic database to a point in time with WAL archivingYou will archive the clinic database's WAL, take a base backup, undo a destructive DELETE by replaying the archive to the second before it ran, and rehearse that restore on a scratch copy.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials