Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท State and Storage

Keeping Bot State in Memory

Learn how Discord and Telegram bots keep state in memory with Maps, counters and TTL caches, and why memory state vanishes on restart and must be bounded.

Every bot needs to remember things: how many messages a user sent, which step of a form a chat is on, which game is running in which channel. The simplest place to keep that is a variable in your program. It is fast and needs no setup, and for a small bot it is often the right first answer.

This lesson shows the in-memory patterns you will use again and again, and the two limits you must respect: memory disappears when the process stops, and memory grows if you never throw anything away.

All examples here use plain Node.js and hand-built update objects shaped like real Telegram and Discord payloads. No bot library is needed, and nothing talks to a real server (the lessons in this track say so wherever a real token would be required).

Why a Map and not a plain object

Bots are keyed by IDs: chat IDs, user IDs, guild IDs. A Map is the right container for that. It keeps insertion order, accepts any key type, has a reliable size, and cannot be tricked by keys like __proto__.

Node.js Per-chat message counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the key is the chat ID, not the user ID. In a group chat, many users share one chat ID. Decide up front what the thing you are counting belongs to: a user, a chat, a Discord guild, or a channel. Mixing these up is the most common state bug.

Composite keys

Some state belongs to a pair, such as "this user in this guild". Discord users exist in many guilds, so a XP counter needs both IDs. Build a string key.

Node.js Composite keys for guild members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

IDs on Discord are 64-bit "snowflakes". JavaScript numbers lose precision above 2^53, so always treat Discord IDs as strings. Telegram IDs fit in numbers, but chat IDs of groups are negative, which is fine for Map keys.

State that expires

Some state is only useful for a short time: a pending confirmation, a cooldown, a "waiting for the user's answer" flag. Store an expiry timestamp next to the value and check it on read. This is called lazy expiry, and it needs no timers.

Node.js A tiny TTL cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The clock is passed in as a function. That makes the class testable, because tests can move the fake clock instead of waiting. Testing bots with fakes uses the same trick.

Cooldowns

A cooldown is just a TTL entry: "this user ran /roll, ignore them until time T".

NODE
const lastUse = new Map();
function onCooldown(userId, cooldownMs, now = Date.now()) {
  const last = lastUse.get(userId) ?? 0;
  if (now - last < cooldownMs) return Math.ceil((cooldownMs - (now - last)) / 1000);
  lastUse.set(userId, now);
  return 0; // 0 means the command may run
}

Return the remaining seconds so the bot can say "try again in 3 s" instead of silently ignoring the user.

Keeping memory bounded

A bot with a million users and a Map that only grows will eventually run out of memory. Two defenses:

  1. Expire things (above), and sweep from time to time with setInterval(...).unref().
  2. Cap the size. A least-recently-used (LRU) cache drops the oldest entry when full. A Map remembers insertion order, so delete-and-reinsert on each read keeps the newest at the end.
Node.js An LRU cache in 12 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

An LRU is perfect for a cache (data you can recompute or reload) and wrong for the only copy of something important.

What memory cannot do

When the process restarts, because of a deploy, a crash or the host moving your container, every Map is empty again. Ask of each piece of state: "Would the user be upset if this vanished?"

  • Cooldowns, typing indicators, cached user names: fine in memory.
  • Balances, warnings, settings, scheduled reminders: not fine. They need a database, which is the next lesson: SQLite storage for bots.

Also remember that two copies of your bot, for example two containers behind a webhook, do not share memory. If you ever scale beyond one process, shared state must live outside the process.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should a Discord user ID be stored as a string in JavaScript?

    Discord snowflakes are 64-bit integers; JavaScript numbers are only exact up to 2^53, so parsing them as numbers corrupts the last digits.
  2. 2. Which state is a bad fit for an in-memory Map only?

    Warnings must survive restarts, and memory is lost whenever the process stops. The other three are short-lived or recomputable.
  3. 3. What does lazy expiry mean?

    The entry stores its expiry time and the read path compares it to the clock, so no timers are needed.
  4. 4. How does the Lru class decide what to evict?

    A Map iterates in insertion order. Reading deletes and re-inserts the key, so the first key is the least recently used.

Summary

  • Use a Map keyed by chat, user, guild or a composite string; decide what the state belongs to first.
  • Treat Discord IDs as strings.
  • Give short-lived state an expiry; check it lazily and sweep occasionally.
  • Cap caches with an LRU so memory stays bounded.
  • Memory is lost on restart and is not shared between processes, so anything valuable needs a database.

Next: SQLite storage for bots