All articles

Warming a Langfuse prompt cache at .NET startup for cold starts

A last-known-good cache in front of Langfuse prompt management protects a .NET service from an outage that starts after the service has already fetched its prompts. It does nothing for a pod that starts during the outage, because that pod has nothing cached yet. The fix I used is a hosted service that resolves every registered prompt name shortly after the host starts, counts a failed fetch as unresolved, and logs one census line such as prompts warmed: 11/12, so a cold start is visible before the first real request needs a prompt.

Where a last-known-good cache stops helping

The service in question fetches its LLM prompts from Langfuse at runtime rather than compiling them in. Each lookup goes through a cache that keeps the last prompt it fetched successfully for 24 hours. If Langfuse is unreachable, the service carries on with the cached copy and logs the failure. That design is sound, and it is easy to stop thinking about it once it is in place.

The gap is in the word "last". A cache can only return what it has seen. Consider the order of events in a real incident:

  • The prompt service has an outage.
  • Something unrelated restarts a pod: a deploy, a node drain, an autoscaler adding capacity because traffic went up.
  • The new pod's cache is empty, so its first request for each prompt goes to a service that isn't answering.

Every pod that was running before the outage is fine. Every pod that starts during it fails on each prompt, and you find out from user-facing errors rather than from anything at startup. Deploys and scale-ups are exactly the events most likely to happen while people are reacting to an incident, so this is not an exotic case.

Why warm up after the host starts, not before

The obvious alternative is to fetch every prompt before the host accepts traffic and refuse to start if any fetch fails. I decided against that. It turns an outage in one dependency into a service that cannot start at all, and it would make deploys hostage to the availability of a prompt store that the running pods were coping without.

Instead, a background service waits for IHostApplicationLifetime.ApplicationStarted, then resolves every prompt name the service has registered. Startup is not delayed, readiness is not tied to it, and if Langfuse is healthy the cache is full a moment later. When Langfuse is down, the pod behaves exactly as it did before, and the log now says so.

This needs one thing the code didn't have: a single list of the prompt names the service uses. Before, the names were scattered across the call sites that requested them. Registering them in one place made warm-up possible, and it also gave a reviewer one file to check when a prompt is added.

How the warm-up service looks

A minimal version, written fresh for this article. IPromptProvider stands for whatever wraps the Langfuse client and its cache; the point is that warm-up goes through the same cached path a real request does.

public sealed class PromptWarmup(
    IHostApplicationLifetime lifetime,
    IPromptProvider prompts,
    PromptRegistry registry,
    ILogger<PromptWarmup> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var started = new TaskCompletionSource();
        using var _ = lifetime.ApplicationStarted.Register(() => started.TrySetResult());
        await started.Task.WaitAsync(stoppingToken);

        var resolved = 0;
        foreach (var name in registry.Names)
        {
            try
            {
                var prompt = await prompts.GetAsync(name, stoppingToken);
                if (prompt is not null) resolved++;
                else logger.LogWarning("Prompt {Name} not resolved during warm-up", name);
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                logger.LogWarning(ex, "Prompt {Name} failed during warm-up", name);
            }
        }

        logger.LogInformation("Prompts warmed: {Resolved}/{Total}", resolved, registry.Names.Count);
    }
}

Registered with services.AddHostedService<PromptWarmup>(). Three details matter more than they look.

Count a failure as unresolved, not as an exception

Warm-up must never take the host down, so every fetch is caught. But a swallowed exception that counts as success is worse than no warm-up at all, because the census would then claim a full cache that isn't there. A failed fetch is logged against its name and left out of the resolved count.

Log the census every time, including the good case

The line Prompts warmed: 12/12 on a healthy start is what gives Prompts warmed: 0/12 its meaning. If the service only logged problems, a pod where warm-up never ran and a pod where everything worked would look the same. I added a test that pins the shape of that line, because it is the thing someone searches for during an incident, and a reworded message breaks their saved query silently.

Treat blank and placeholder credentials as missing

If the Langfuse keys arrive empty, or as an unsubstituted secret-store placeholder, every warm-up fetch fails with an authentication error that looks like an outage. A small shared helper recognises both forms so the service can report misconfiguration as misconfiguration, rather than as a dependency being down.

What warm-up does not fix

Warm-up runs once per process. The cache entries it creates expire after the same 24 hours as any other entry, so a prompt that no request asks for in that time goes cold again, and a pod that has been running for days is back to depending on the prompt store for that name. I accepted that: the prompts that matter are requested constantly, and a periodic refresh adds a scheduler, its own failure modes and a steady stream of background calls, for a case that hasn't come up.

It also doesn't help a pod that starts during an outage and stays up past it with nothing cached. That pod recovers on its own the first time a request fetches successfully, which is the behaviour it had before; warm-up only removes the window in the common case.

If you need a stronger guarantee, the next step is not a cleverer cache but a bundled fallback: ship a known-good copy of each prompt with the build and use it when both the cache and the store come up empty. That trades freshness for availability, and it reintroduces the question of which copy is the source of truth, so it is a decision rather than a free upgrade.

Key takeaways

  • A last-known-good cache only protects processes that were warm before the outage began, so pods started by a deploy or a scale-up during an incident get nothing from it.
  • Warming the cache in a hosted service after ApplicationStarted fills it without tying startup or readiness to the prompt store's availability.
  • Keep every prompt name the service uses in one registry, so warm-up can resolve them all and reviewers can see them in one place.
  • Log a resolved/total census on every start and count a failed fetch as unresolved, so a healthy start and a broken one never look alike.
  • One-off warm-up still lets rarely used prompts go cold after the cache lifetime; a bundled fallback copy is the next step if that matters.

Written by Artem Shymko, a senior software engineer in Belgium working on Drupal, .NET and LLM features. Get in touch if you are working on something similar.

  • .NET
  • Langfuse
  • LLM
  • Resilience