Optimizing API Interactions—Receiver
Learn how to improve API interactions as a receiver.
Let us look at how we would optimize our API interactions if we owned the routes that accept incoming traffic. Essentially, we want to be able to receive a request, process it swiftly, and respond efficiently, all in as little time as possible. Let’s take a look at how we could do that.
Use caching effectively
We discussed caching as a caller, but what about as a receiver? If we serve resources that don’t change frequently, we must consider caching them ourselves! There are two ways in which caching concepts can be applied.
Using in-memory or external cache
An in-memory cache should suffice for smaller data sizes, but consider using an external cache, like Redis, for larger datasets. We could cache the data we want to serve corresponding to a query in a data store easily accessible to us instead of having to compute the entire result set again. This is especially useful when we have heavy computation or database queries involved.
Using ETags
ETags, short for entity tags, are used to verify the freshness of an HTTP response and help ensure cache consistency across distributed systems. They are essentially a string of characters assigned by a server to a specific resource and returned to the client as an HTTP header. The client can send this ETag back to the server in a subsequent request to verify whether the resource has changed since.
ETags are generated using a hash of the resource’s content, its last modified time, or a combination of both. They are handy for resources that change frequently or whose response size is large, even if not computationally heavy. This allows for optimized caching and saves network bandwidth because we don’t fetch the same resource from the server if it hasn’t changed.
To use ETags in our server, we can simply use chi’s middleware, which provides us the functionality in a neatly packaged middleware function out of the box.
Get hands-on with 1400+ tech skills courses.