Can I use Env for caching database results?

The HelloWorld worker example recommends using the Env object to store the router which is initialized once and never modified:
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if(env.router === undefined) env.router = buildRouter(env);
return env.router.handle(request);
}
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if(env.router === undefined) env.router = buildRouter(env);
return env.router.handle(request);
}
My API depends on some database values (policies) which are very rarely changed, but when they do, they need to be respected immediately and everywhere. I thought of using Env for this as well and modified the above to:
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if(env.router === undefined) env.router = buildRouter(env);
if(env.policies === undefined) env.policies = await fetchPolicies(env);
return env.router.handle(request);
}
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if(env.router === undefined) env.router = buildRouter(env);
if(env.policies === undefined) env.policies = await fetchPolicies(env);
return env.router.handle(request);
}
and I defined a /refresh API that I will call explicitly when policies change in db like this:
router.get("/refresh", async (request) => {
env.policies = await fetchPolicies(env);
return new Response("policies refreshed!");
});
router.get("/refresh", async (request) => {
env.policies = await fetchPolicies(env);
return new Response("policies refreshed!");
});
This seems to work fine locally. But I am not sure if this will work correctly in production. Given that the worker isolates are deployed at multiple locations across the globe, my /refresh API will only reach one of the worker instances and all other instances will continue to have stale data in their env.policies. Is there a way to cache DB values while able to invalidate them globally at once?
1 Reply
honzabit
honzabit17mo ago
you correctly answered that this will not work as you wish, you need to check Durable Objects for this use-case
Want results from more Discord servers?
Add your server