Lazy hydration from storage

--

You don’t always want to maintain state in durable object instance properties, but if you do, you need to rehydrate them when your durable object (DO) is reinstantiated. This is because an inactive DO can be ejected from memory at any time. Cloudflare’s documentation describes using state.blockConcurrencyWhile() in your constructor to accomplish this. However, I’ve found a way that I like better.

Why do I like this over using state.blockConcurrencyWhile() in the constructor?

Several reasons:

  1. It gives you a chance to do input checking on the request before calling await this.hydrate(). Why incur the cost of storage operations if the request is malformed. Just return early with the error.
  2. Some requests don’t require rehydration. I usually have a “static” route that just returns the schema for the DO (later post) which doesn’t need hydration. Http OPTIONS method calls, which are important for pre-flight CORS checks also don’t require rehydration. DO’s are never accessed directly so you might not think CORS checks are important but another pattern that I use (subject of a later post) is a Worker or Pages proxy that gives the DO responsibility for responding to all requests including OPTIONS ones.

--

--

Larry Maccherone
Cloudflare Durable Objects Design Patterns

Every decision is a forecast. You are forecasting that the alternative you chose will have better outcomes.