Skip to content
Recipes

Cache

What is cache?

Cache is a temporary storage layer that keeps frequently accessed data readily available for quick access. In Seyfert, the cache system stores Discord data in memory by default, though it can be configured to use other storage solutions like Redis.

Resources

All entities supported by Seyfert's cache are resources, such as channels, users, members, etc. Each of these resources is managed in the same way, but they can be modified and handled differently depending on the Adapter.

Disabling

Seyfert allows you to disable these resources separately.

Global Data

In Seyfert, the cache is global, meaning everything is stored in the same resource, with no distinction between guilds, until they are retrieved, at which point you would need to specify the source.

ResourceElements
channelsTextChannel, DMChannel, VoiceChannel, ThreadChannel...
bansGuildBan
emojisEmoji
guildsGuild
messagesMessage
overwritesPermissionsOverwrites
presencesPresence
membersGuildMember
rolesGuildRole
usersUser
stickersSticker
voiceStatesVoiceStates
stageInstancesStageChannel
import { Client } from 'seyfert';

const client = new Client();

client.setServices({ cache: { disabledCache: { bans: true } } })

The example above disables the bans cache, and that resource would not exist at runtime.

Disabling Gateway Writes

You can stop gateway packets from writing data into the cache:

client.setServices({ cache: { disabledCache: { onPacket: true } } })

Filtering

You can filter which data gets stored in a resource. For example, if your application doesn't need to cache DM channels, you can filter them out:

index.ts
import { Client } from "seyfert";
import { type APIChannel, ChannelType } from "seyfert";
const client = new Client();

client.cache.channels!.filter = (
    channel,
    id,
    guildId,
) => {
    return ![
        ChannelType.DM,
        ChannelType.GroupDM
    ].includes(channel.type);
};

What gateway events write

Gateway payloads fill the resources as they arrive. From Seyfert 6.0.0, the users and members resources also receive the users and members carried by interactions, messages and their mentions, reactions, typing and voice state updates, so a member who only ever ran a command can be read from the cache afterwards.

Cache queries

members.list(), bans.list(), guilds.list() and members.search() can answer a query from the cache instead of requesting Discord. From Seyfert 6.0.0 this is on by default.

// The 50 cached members with the lowest ids after the cursor.
const page = await client.members.list(guildId, { limit: 50, after: '366779196975874049' });

// Cached members whose username or nickname starts with "soc".
const matches = await client.members.search(guildId, { query: 'soc', limit: 10 });

A list call without a query still returns every cached entry of that guild.

CallThe cache can answerDefault limit
members.list()limit and after1
bans.list()limit, before and after1000
guilds.list()limit, before and after; with_counts: false200
members.search()query as a case-insensitive prefix of the username or nickname, and limit1

Seyfert requests Discord instead when the cache cannot answer:

  • the resource is disabled or holds no entries to page through;
  • the query uses another parameter, such as with_counts: true or shard in guilds.list(), or a limit Discord would reject;
  • an id selected for the page is missing from the cache;
  • a member search matches nothing.

The cache answers from what it holds

A cached page is built from the entries currently in the cache. If a guild's members are only partly cached, the page comes from that part. Pass { force: true } when the result has to be complete.

Turn the behavior off for the whole client, per resource, or for one call:

const client = new Client();

// Every query goes to Discord.
client.setServices({ cache: { queries: false } });

// Only member search goes to Discord; omitted resources stay enabled.
client.setServices({ cache: { queries: { memberSearch: false } } });

// One call: skip the cached query, or skip the cache entirely.
await client.bans.list(guildId, { limit: 100 }, { cacheQuery: false });
await client.members.list(guildId, { limit: 100 }, { force: true });

queries also accepts a function that receives 'members', 'memberSearch', 'bans' or 'guilds' and returns a boolean. A per-call cacheQuery: true enables the cached query even when the client has it disabled.

Guild member counts

Discord sends member_count only in GUILD_CREATE, so guild.memberCount normally stays at the value it had when the shard connected. From Seyfert 6.0.0, trackMemberCount keeps it current by adjusting the cached count on every member join and leave.

It is off by default. Turn it on before connecting, with both the Guilds and GuildMembers intents:

import { Client } from 'seyfert';

const client = new Client();

client.setServices({
    cache: {
        trackMemberCount: true,
    },
});

await client.start({
    connection: {
        intents: ['Guilds', 'GuildMembers'],
    },
});

Guilds delivers the GUILD_CREATE that seeds each count, and GuildMembers delivers the joins and leaves. While tracking is on, Seyfert applies the cache writes of one guild in the order its packets arrived, so a count change cannot land on a newer guild snapshot. That ordering is local to the client that receives the guild's events, including when its adapter stores data in shared storage such as Redis.

Adapters

Seyfert allows you to provide your own adapter for the cache, which you can think of as a driver to let Seyfert use an unsupported tool. By default, Seyfert includes MemoryAdapter and LimitedMemoryAdapter, both of which operate in RAM. Additionally, Seyfert has official Redis support through the Redis Adapter.

Difference between MemoryAdapter and LimitedMemoryAdapter

The MemoryAdapter stores all data in memory, while the LimitedMemoryAdapter limits the amount of data stored in memory by providing expiration times and limits of entries.

LimitedCollection

Seyfert also ships a LimitedCollection, a TTL-based key-value collection handy for temporary data outside the resource cache:

import { LimitedCollection } from 'seyfert';

const cache = new LimitedCollection<string, { score: number }>();

// Set with auto-expiry (3rd argument is TTL in ms)
cache.set('user-123', { score: 42 }, 60_000); // Expires in 60s

// Get (returns undefined if expired)
const item = cache.get('user-123');

// Check existence
cache.has('user-123');

Building Your Own Cache

Custom Resource

A custom resource is just a new cache entity, so integrating it is relatively simple. Let's take the example of the Cooldown resource from the cooldown package.

It's important to note that Seyfert provides a base for three types of resources:

  • BaseResource: a basic entity, which should be completely independent
  • GuildBasedResource: an entity linked to a guild (like bans)
  • GuildRelatedResource: an entity that may or may not be linked to a guild (like messages)
resource.ts
import { BaseResource, CacheFrom } from 'seyfert';

interface CooldownData {
    id: string;
    lastDrip: number;
}

type CooldownInput = Omit<CooldownData, 'lastDrip'> & Partial<Pick<CooldownData, 'lastDrip'>>;

export class CooldownResource extends BaseResource<CooldownData, CooldownInput> {
    // The namespace is the base that separates each resource
    namespace = 'cooldowns';

    // We override set to apply the typing and format we want
    override set(from: CacheFrom, id: string, data: CooldownInput) {
        return super.set(from, id, { ...data, lastDrip: data.lastDrip ?? Date.now() });
    }
}

Note that a custom resource is for developer use; Seyfert will not interact with it unless specified in the application's code.

import { Client, type ParseClient } from 'seyfert';
import { CooldownResource } from './resource'

const client = new Client();

client.cache.cooldown = new CooldownResource(client.cache, client);

declare module "seyfert" {
    interface Cache {
        cooldown: CooldownResource;
    }
    interface SeyfertRegistry { client: ParseClient<Client> }
}

Custom Adapter

Don't like storing the cache in memory or Redis? Implement the Adapter interface to back the cache with anything you like.

If your adapter is asynchronous, set isAsync = true and return promises from its methods (a synchronous adapter simply returns values directly). The start method runs once before the bot starts and may always be async.

Seyfert's cache stores values keyed by a dotted path, plus relationships (sets of IDs) so it can tell who a resource belongs to. Keys look like this:

<resource>.<id2>.<id1> // member.1003825077969764412.366779196975874049
<resource>.<id1>       // user.576805413148688424

Implementing the Adapter interface

Below is a complete async skeleton backed by an imaginary storage driver. Methods are grouped by purpose; the bulk* variants just loop over their single-item counterparts, and keys/values/count/contains derive from a relationship.

import { Adapter, type AdapterEntry, type AdapterRelationship } from 'seyfert';

class MyAdapter implements Adapter {
    isAsync = true;

    async start() {
        // Runs before the bot starts
    }

    // --- Storing values ---
    async set(key: string, value: any | any[], relationship: AdapterRelationship) {
        await this.storage.set(key, value, relationship);
    }

    async bulkSet(entries: AdapterEntry[]) {
        for (const entry of entries) await this.set(...entry);
    }

    // patch only overwrites the properties you pass, not the whole value
    async patch(key: string, value: any | any[], relationship: AdapterRelationship) {
        await this.storage.patch(key, value, relationship);
    }

    async bulkPatch(entries: AdapterEntry[]) {
        for (const entry of entries) await this.patch(...entry);
    }

    // --- Retrieving values ---
    async get(key: string) {
        return this.storage.get(key);
    }

    async bulkGet(keys: string[]) {
        const values = await Promise.all(keys.map(key => this.get(key)));
        return values.filter(value => value); // drop nulls
    }

    // --- Reading/removing relationships (sets of unique IDs) ---
    async getToRelationship(to: string) {
        return await this.storage.setGet(to) ?? [];
    }

    async removeToRelationship(to: string, key: string | string[]) {
        await this.storage.setPull(to, Array.isArray(key) ? key : [key]);
    }

    async removeRelationship(to: string | string[]) {
        for (const target of Array.isArray(to) ? to : [to]) {
            await this.storage.setRemove(target);
        }
    }

    // Derived helpers built on get + getToRelationship
    async keys(to: string) {
        return (await this.getToRelationship(to)).map(key => `${to}.${key}`);
    }

    async values(to: string) {
        const values = await Promise.all((await this.keys(to)).map(key => this.get(key)));
        return values.filter(value => value);
    }

    async count(to: string) {
        return (await this.getToRelationship(to)).length;
    }

    async contains(to: string, key: string) {
        return (await this.getToRelationship(to)).includes(key);
    }

    // --- Deleting ---
    async remove(key: string) {
        await this.storage.remove(key);
    }

    async bulkRemove(keys: string[]) {
        for (const key of keys) await this.remove(key);
    }

    async flush() {
        await this.storage.flush();    // values
        await this.storage.setFlush(); // relationships
    }

    // --- scan: see below ---
    async scan(query: string, keys?: false): any[];
    async scan(query: string, keys: true): string[];
    async scan(query: string, keys = false) {
        const values: (string | unknown)[] = [];
        const sq = query.split('.');
        for (const [key, value] of await this.storage.entries()) {
            const match = key.split('.')
                .every((part, i) => (sq[i] === '*' ? !!part : sq[i] === part));
            if (match) values.push(keys ? key : value);
        }
        return values;
    }
}

Atomic increments

increment is an optional method. Seyfert 6.0.0 uses it to update a guild's member_count when trackMemberCount is enabled:

    // Inside MyAdapter
    async increment(key: string, field: string, delta: number, options?: AdapterIncrementOptions) {
        return this.storage.increment(key, field, delta, options?.min);
    }

Implement it only when the backend can do the whole update atomically. The method must:

  • add delta to an existing numeric field of an existing object value and return the new value, clamped to options.min when it is set;
  • return undefined without writing when the key is missing or expired, the value is not an object, or the field is missing or not a number;
  • keep the other fields and the relationship of the entry;
  • reject without writing when delta, options.min or the result is not a finite number.

A get followed by a patch is not atomic, so leave increment out in that case. Seyfert then reads the guild and patches the new count itself, in the per-guild order described above. MemoryAdapter and LimitedMemoryAdapter implement it, and WorkerAdapter exposes it when the manager's backend does.

The scan method

scan is the one non-trivial method. It takes a query matching the dotted key format, where * means "any ID":

<resource>.<*>.<*> // member.*.*
<resource>.<*>.<id> // member.*.366779196975874049
<resource>.<id>.<*> // member.1003825077969764412.*
<resource>.<*> // user.*

It must return every match (values, or keys when the second argument is true). The skeleton above iterates over all entries, which works but is slow; a real backend should push the matching down into the store, like our Redis adapter does.

Example of Redis Adapter

Testing

To ensure your adapter works, run the testAdapter method from Cache.

import { Client } from 'seyfert';

const client = new Client();

client.setServices({
    cache: {
        adapter: new MyAdapter()
    }
})

await client.cache.testAdapter();