Caching & Structures
Lunibee manages Discord resources (Users, Guilds, Channels, Roles, Messages) using Canonical Identity Caching.
Canonical Identity Guarantee
Section titled “Canonical Identity Guarantee”When a resource is received via a Gateway event (or a channel is fetched via REST), the resource manager checks if an existing instance already exists in memory.
If it exists, Lunibee mutates the existing structure in place and returns the same object reference. This includes fetch() on every manager: a fetched resource is merged into the cached instance. This prevents subtle desynchronization bugs where two parts of your application hold different versions of the same guild or user.
const channelA = client.channels.cache.get("123456789012345678");const channelB = await client.channels.fetch("123456789012345678");
console.log(channelA === channelB); // true! Exact same instanceconst channelA = client.channels.cache.get("123456789012345678");const channelB = await client.channels.fetch("123456789012345678");
console.log(channelA === channelB); // true! Exact same instanceResource State Never Expires
Section titled “Resource State Never Expires”Every manager cache is a Collection. Managers store Discord resources with
setWithoutTTL(), so a guild, channel, role, member or user leaves the cache
only through an explicit delete — a Gateway *_DELETE event or your own
manager.delete(id) — never because nobody read it. The one opt-in exception
is cache.maxMembers, which evicts each guild’s least recently used members.
Gateway events keep the caches current: GUILD_CREATE fills roles, emojis,
members and channels; updates merge into the cached object; GUILD_DELETE
removes the guild with its channels and per-guild managers.
client.guilds.members(guildId).get(userId); // GuildMemberclient.guilds.roles(guildId).get(roleId); // Roleclient.guilds.emojis(guildId).cache.size;A REST fetch that finishes after a Gateway update (or delete) for the same resource is not cached, so it cannot overwrite newer state: you get the cached object (or the fetched one if the resource was deleted). Concurrent fetches of one resource share a single request.
TTL & LRU Collections for Your Own Data
Section titled “TTL & LRU Collections for Your Own Data”Collection doubles as a bounded cache for application data:
import { Collection } from "lunibee";
const cooldowns = new Collection<string, number>(null, { ttl: 60_000, // sliding: each get() restarts the window maxSize: 10_000, // least-recently-used set() entries are evicted onEvict: (key, value, reason) => console.debug(key, reason), // "expired" | "evicted"});
cooldowns.set(userId, Date.now()); // TTL/LRU entrycooldowns.set(userId, Date.now(), 5_000); // per-entry TTLcooldowns.setWithoutTTL("pinned", 0); // never expires, never evictedcooldowns.peek(userId); // read without sliding the TTLcooldowns.stats; // { hits, misses, expired, evicted }Messages Are Not Cached by Default
Section titled “Messages Are Not Cached by Default”Messages are temporary data. Enable a bounded per-channel cache only if you need the previous content on edits and deletes:
const client = new Client({ token, intents, messageCache: { maxSize: 200, ttl: 30 * 60_000 },});Turning Caches Off on Large Bots
Section titled “Turning Caches Off on Large Bots”Events still carry full objects when a resource is not cached:
const client = new Client({ token, intents, cache: { members: false, users: false }, // roles and emojis stay cached});Shared Cache in Redis
Section titled “Shared Cache in Redis”For your own data shared between processes (sessions, cooldowns, counters), use RedisCollection. For Discord’s data, read on.
The in-memory cache of each process holds only the guilds its own shards receive. RedisCache mirrors the same Gateway events into Redis, so another cluster, a dashboard or a worker without a Gateway can read any guild. It sits beside the in-memory cache and changes nothing about it: client.guilds.get(id) stays synchronous.
import { Client, RedisCache } from "lunibee";
const shared = new RedisCache({ client: new Bun.RedisClient(process.env.REDIS_URL!), // ioredis: { send: (c, a) => redis.call(c, ...a) } prefix: "mybot:cache:", // default "lunibee:cache:"; keys live under <prefix>v1: members: true, // default; false skips members and their users ttlSeconds: 86_400, // optional: expire keys a day after their last write onError: (event, error) => console.warn("cache write failed", event, error),});shared.attach(client); // or shared.attach(gateway) for each shard
// In any process with the same Redis:const guild = await shared.guild(guildId);const channels = await shared.channels(guildId);const member = await shared.member(guildId, userId); // with .user| Read | Returns |
|---|---|
guild(id) |
The guild payload, without its channels, roles, members and presences. |
guildIds() |
Every cached guild id. |
channel(id) / channels(guildId) |
A channel or thread (with guild_id) / all of a guild’s. |
role(guildId, id) / roles(guildId) |
One role / all of a guild’s. |
member(guildId, userId) / members(guildId) |
A member with its user / every cached member (mind the size of large guilds). |
user(id) |
A user. |
Values are raw Discord payloads; pass a type to read them typed: shared.guild<APIGuild>(id).
- Events mirrored:
GUILD_CREATE(a full snapshot that replaces what was stored),GUILD_UPDATE,GUILD_DELETE(an outage keeps the data markedunavailable; leaving drops it), channel and thread create/update/delete, role create/update/delete, member add/update (merged, since updates are partial)/remove,GUILD_MEMBERS_CHUNK, emoji and sticker updates,USER_UPDATE. Messages and presences are not stored. - Ordering: one guild’s writes are applied in Gateway order; users, shared by every guild, are written on one chain in Gateway order.
- Failures: a failed write is counted (
diagnostics()), passed toonErrorand never thrown into the Gateway; reads throw on a Redis error.flush()resolves when every queued write is done. - Freshness: each process writes the guilds of its own shards. A guild the bot left while no process was connected stays until a
ttlSecondsexpiry; set one if that matters. handle(event, data)applies one dispatch directly, for events relayed from elsewhere.
Structure Resource Methods
Section titled “Structure Resource Methods”Structures like Message, Guild, and Channel expose intuitive helper methods that automatically route through the manager’s REST client:
client.on("messageCreate", async (message) => { // Directly edit the message await message.edit({ content: "Updated content!" });
// Or delete it await message.delete();});client.on("messageCreate", async (message) => { // Directly edit the message await message.edit({ content: "Updated content!" });
// Or delete it await message.delete();});Channel Classes
Section titled “Channel Classes”Channels built by the client and managers use createChannel(data), which returns the
most specific class. All of them extend Channel.
| Type | Class |
|---|---|
| Text (0) | TextChannel |
| DM (1), Group DM (3) | DMChannel (recipients, ownerId) |
| Voice (2) | VoiceChannel (bitrate, userLimit, rtcRegion) |
| Category (4) | CategoryChannel |
| Announcement (5) | NewsChannel |
| Threads (10, 11, 12) | ThreadChannel (archived, locked, messageCount, ownerId) |
| Stage (13) | StageChannel |
| Forum (15) | ForumChannel (availableTags, …) |
| Media (16) | MediaChannel |
Every channel has isThread(), isTextBased(), isVoiceBased() and isDMBased().
Guild Resource Managers
Section titled “Guild Resource Managers”| Access | Manager | Covers |
|---|---|---|
client.guilds.bans(guildId) |
GuildBanManager |
fetch, fetchAll, create, bulk, remove |
client.guilds.scheduledEvents(guildId) |
GuildScheduledEventManager |
fetch, fetchAll, create, edit, remove, fetchSubscribers |
client.channels.permissionOverwrites(channelId) |
PermissionOverwriteManager |
update, edit, remove |
client.stageInstances |
StageInstanceManager |
create, fetch, edit, remove |
await client.guilds.bans(guildId).create(userId, { deleteMessageSeconds: 3600, reason: "Spam",});The ban, scheduled-event and stage-instance managers cache raw Discord payloads.