DEV Community

Castanderness
Castanderness

Posted on

SQLite vs Redis for Telegram Bots: When to Use What

SQLite vs Redis for Telegram Bots

Choosing the wrong database can tank your bot's performance.

SQLite: The Default Choice

import sqlite3

conn = sqlite3.connect('bot.db')

def get_user(chat_id: int) -> dict | None:
    row = conn.execute(
        'SELECT * FROM users WHERE chat_id=?', (chat_id,)
    ).fetchone()
    return dict(row) if row else None
Enter fullscreen mode Exit fullscreen mode

Use SQLite when: < 1000 users, persistent storage (orders, settings), single-server deployment.

Redis: For Speed and Expiry

import redis

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

# Store FSM state with 1-hour expiry
def set_state(chat_id: int, state: str):
    r.setex(f'state:{chat_id}', 3600, state)

# Rate limiting - 5 requests per minute
def is_rate_limited(chat_id: int) -> bool:
    key = f'rate:{chat_id}'
    count = r.incr(key)
    if count == 1:
        r.expire(key, 60)
    return count > 5
Enter fullscreen mode Exit fullscreen mode

Use Redis when: Rate limiting, FSM state, caching API responses.

Quick Decision Guide

Scenario Choice
User profiles SQLite
FSM states Redis
Rate limiting Redis
Transaction records SQLite

Need a production bot with proper database design? I'm available: https://castanderness.github.io/telegram-bots-portfolio/portfolio/

From $59 | 3-5 days delivery

Top comments (0)