DEV Community

SQLite vs Redis for Telegram Bots: When to Use What

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

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

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

Comments

No comments yet. Start the discussion.