Skip to content
White / YV

Deep dive 3 min read

Cache-first lookups in an event-driven bot

Why one task per event and a cache-first read path were the right shape for an alpha Rust bot, and what that choice costs later.

Published

Asuka RS is an alpha Rust side project, an event-driven Discord bot with cache-first lookups, localized responses, and support for 31 locale codes. Two decisions inside it generalise well beyond bots. This note is about those two decisions and what they cost.

One task per event instead of one handler for everything

The naive shape for a gateway consumer is a single loop with a big match. That works until one branch does something slow or panics, and then the loop serving every other event is what stopped.

The fix is to make the receive loop do almost nothing except hand work off.

while let Some(event) = shard.next_event(EventTypeFlags::all()).await {
    let Ok(event) = event else { continue };
    let ctx = ctx.clone();
    tokio::spawn(async move {
        if let Err(error) = handle_event(ctx, event).await {
            tracing::warn!(?error, "event handler failed");
        }
    });
}

Two things follow. Failure is contained. A handler that returns an error gets logged, and the next event never notices. And slow work stops blocking fast work, because a task waiting on the database does not hold the receive loop.

The cost is real. An unbounded spawn means unbounded concurrency. A burst produces as many tasks as there are events, and ordering between events stops being guaranteed. For an alpha with human-paced traffic, that trade is fine. At larger scale it becomes a bounded worker pool plus a queue. Plan for it instead of being surprised by it.

Cache-first reads, and the invalidation you must not skip

Nearly every interaction needs the same small pieces of state, such as a user’s preferences or a server’s configuration. Reading those from disk every time is wasted work, so the read path checks an in-memory cache first.

async fn user(&self, id: UserId) -> Result<User> {
    if let Some(user) = self.users.get(&id).await {
        return Ok(user);
    }

    let user = self.db.find_user(id).await?.unwrap_or_default();
    self.users.insert(id, user.clone()).await;
    Ok(user)
}

The read itself is the easy part. Every write has to invalidate or update the same key, and that is where cache-first designs actually break.

async fn set_locale(&self, id: UserId, locale: Locale) -> Result<()> {
    self.db.update_locale(id, locale).await?;
    self.users.invalidate(&id).await;   // not optional
    Ok(())
}

Miss that one line and you get the worst kind of bug. A user changes a setting, the write succeeds, and the bot keeps behaving as if it had not, intermittently, depending on the node or the TTL window they hit. Write the invalidation in the same function as the write, never in a separate “cache layer” that someone can forget to call.

A bounded cache with a TTL turns a missed invalidation from permanent corruption into a bounded staleness window. That is a safety net, not a design.

Process flow The read path. The dashed edge is the one you pay for, and the one invalidation exists to keep honest.

Localization as a lookup, not a branch

At 31 locale codes, string formatting stops being incidental. One rule keeps it manageable. User-facing text is never built inside handler code. The handler resolves a locale and asks for a key.

let locale = user.locale.unwrap_or(guild.locale);
let message = self.i18n.lookup(&locale, "command.ping.response");

English is always the fallback. A missing translation degrades to a language the reader may not prefer, which is inconvenient but usable; a missing translation that panics or renders an empty string is a broken bot. Coverage across those 31 codes can be incomplete (the honest state of an alpha), and the fallback is what makes that survivable.

What I would do differently

Independent event tasks were the right concurrency model for the MVP, and they made the next requirement obvious instead of hiding it. Once you cannot see how many tasks are in flight, you need real operational tooling. An API and a dashboard belong before a broader release.

The general lesson is to pick the concurrency model that contains failure first, and treat the observability it demands as part of the same decision rather than something to add later when it hurts.