How to improve REST API performance and handle concurrency? - Part 5
Improve REST API performance with Cache-Control, conditional GET, ETag and compression, and handle concurrency with optimistic locking.
How to improve REST API performance and handle concurrency? - Part 5
Consumers can make whatever API requests they want, whenever they want. Sometimes, consumers repeat the same requests again and again for the same response representation, and it is a waste of time and resources to build the response every time. On the other side, when two consumers update the same resource at the same time, one of them can silently overwrite the other’s change. Interestingly, HTTP solves both problems with the same idea: validators like ETag. In the previous article, we discussed error handling and security. In this article, we are going to see how to improve the API performance with caching, conditional GET and compression, and how to handle concurrency with conditional requests.
REST API Design Guidelines series:
- Why REST and what makes an API RESTful?
- How to design resources and URIs for a REST API?
- How to use verbs, representations and status codes in a REST API?
- How to handle errors and secure a REST API?
- How to improve REST API performance and handle concurrency? (this article)
- How to handle long running requests, versioning, testing and documentation in a REST API?
TL;DR Summary
- Every API response should contain a Cache-Control header which clearly says whether it is cacheable or not, and for how long at the client and the proxy.
- Use conditional GET with ETag when you can’t decide the stale time of a resource; the server sends 304 (Not Modified) without a body when nothing has changed.
- Enable compression for all API responses which have a body.
- Use optimistic concurrency control (ETag with If-Match) for PUT and DELETE, and for POST when it updates a resource.
Performance
HTTP defines some techniques to improve performance, and those techniques are,
- Caching
- Conditional GET
- Compression
Caching
Caching is one of the performance improvement techniques. We can take advantage of caching to reduce the latency, to increase reliability, to reduce bandwidth usage and cost, and to reduce server load. Caches can sit anywhere; they can be in server networks, content delivery networks or in the client network. This feature is only applicable to the GET verb. Caching is a complex topic to discuss, however we will discuss the Cache-Control header here.
Cache-Control: <cacheability>, <expiration>, <revalidation>
Cacheability
- public - This directive instructs that any cache may store the response, either in a proxy or on the client side.
- private - This directive instructs that the response message is intended for a single user (client) and it should not be stored in a shared cache like a proxy.
- no-store - This directive instructs that any cache must not store the response.
Expiration
- max-age=<seconds> - This directive indicates that the response is to be considered stale after its age is greater than the specified number of seconds. Normally, the client or browser will obey this directive. Use this directive to cache a resource at the client.
- s-maxage=<seconds> - This directive indicates that the response cached in a proxy is to be considered stale after its age is greater than the specified number of seconds. Use this when you want to cache a resource at the proxy (in our case, Cloudflare) for a specific period.
- no-cache - This directive indicates that the response must not be served from the cache without successful validation with the origin server. Use this when you don’t want to serve a specific resource from the cache without checking with the server first.
Revalidation
- must-revalidate - This directive indicates that once the response becomes stale, a cache (client or proxy) must not use the response to serve the content without validating with the origin server.
- proxy-revalidate - This directive indicates that once the response becomes stale at the proxy, then the proxy must not use the response to serve the content without validating with the origin server.
- stale-while-revalidate=<seconds> - It indicates that caches may serve the response after it becomes stale, up to the specified number of seconds, while they revalidate it in the background.
- stale-if-error=<seconds> - It indicates that when an error is encountered, a stale cached response may be used to satisfy the request, regardless of other freshness information.
Examples
-
Cache the response for one minute at the client end,
Cache-Control: private, max-age=60 -
Don’t serve the response from the cache without validating it with the server,
Cache-Control: no-cache -
Strictly don’t store the response in any cache,
Cache-Control: no-store -
Cache the response for one minute in the client and 10 minutes in the proxy,
Cache-Control: public, max-age=60, s-maxage=600
Must Be Aware: Define the cache policy clearly and separately for the client and the proxy. Inappropriate middleware caching can send a stale state of a resource to the consumer.
Conditional GET
Sometimes we don’t know when a resource’s state will change. It might change all the time, or it might change so rarely that we can’t estimate how often a change happens. Either way, you can’t decide on a max-age value, so you can’t tell the client to stop making requests for that resource for a while. Instead, you can let the client make its request whenever it wants and eliminate the server’s response if nothing has changed.
This feature is called a conditional request, and to support it, you will need to serve the Last-Modified or ETag header with your representation. The Last-Modified header tells the client when the state of this resource last changed.
How conditional GET request works with Last-Modified?
- Client sends a request to the server.
- Server sends the response with the Last-Modified header.
- Client receives the response and makes a note of the Last-Modified value.
- Client puts the Last-Modified value into the If-Modified-Since header and sends it to the server in the next request.
- Server checks whether the given resource has changed since the given date.
- When the resource state has changed, then the server sends the current state of the resource with the Last-Modified date and 200 status code.
- When the resource state has not changed, then the server sends the 304 (Not Modified) status without any body content.
This saves both parties time and bandwidth. The server doesn’t have to send the response and the client doesn’t have to receive it. But this approach requires tracking the Last-Modified date and it adds some complexity at the API level. There is another strategy which is easier to implement than Last-Modified. The ETag header contains a hash of the response representation and it must change whenever the corresponding representation changes.
How conditional GET request works with ETag header?
- Client sends a request to the server.
- Server sends the response with the ETag header.
- Client receives the response and makes a note of the ETag value.
- Client puts the ETag value into the If-None-Match header and sends it to the server in the next request.
- Server compares the hash of the resource’s current state with the hash provided through If-None-Match.
- When the resource state has changed, then the server sends the current state of the resource with the state hash in the ETag header and 200 status code.
- When the resource state has not changed, then the server sends the 304 (Not Modified) status without any body content.
Example:
GET /api/funds/HI34 HTTP/1.1
Host: api.example.com
HTTP/1.1 200 OK
ETag: "<hash of the representation>"
Content-Type: application/json
{ ...fund representation... }
GET /api/funds/HI34 HTTP/1.1
Host: api.example.com
If-None-Match: "<hash of the representation>"
HTTP/1.1 304 Not Modified
ETag: "<hash of the representation>"
Serving Last-Modified requires that we keep track of a lot of timestamps, but we can generate an ETag for a representation without tracking any extra data.
Must Consider: You must consider using the conditional GET request with the ETag header when you are not able to decide the stale time for a resource, especially for performance and price values in the mutual fund domain. It saves some time and latency, since the server is not required to send the data and the client is not required to receive it when the state of a resource has not changed.
Compression
Textual representations like JSON and XML documents can be compressed to a fraction of their original size. It saves some latency, since the compression eliminates some bytes, so they are not required to be transferred across the wire.
How it works?
- Client sends a request to the server with the Accept-Encoding header (like gzip, deflate, br, etc.).
- Server compresses the response with any one compression method from Accept-Encoding.
- Server sends the compressed response and the Content-Encoding header with the value of the compression encoding.
- Client receives the response and decompresses the content based on the Content-Encoding header.
GET /api/funds HTTP/1.1
Accept-Encoding: gzip, deflate, br
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: gzip
Must Do: It is mandatory to enable compression by default for all APIs. You can use gzip for JSON, XML and other textual data. Use br (Brotli compression) for HTML responses; it uses a built-in dictionary of common HTML words and tags, and it produces a higher compression rate than other compression algorithms.
Concurrency
Conditional requests in HTTP help address two problems. For GET requests, conditional requests help clients and caches validate that a cached representation can still be considered fresh, as we saw above. For unsafe requests such as PUT, POST and DELETE, conditional requests provide concurrency control.
When we don’t apply concurrency control for unsafe POST, PUT and DELETE methods, it may affect the integrity of the application. In the absence of adequate concurrency control checks, the server is susceptible to “lost updates” and “stale deletes”. Concurrency control ensures the correct processing of data under concurrent operations by clients. There are two ways to implement concurrency control,
- Pessimistic Concurrency Control - In this model, the client gets a lock, obtains the current state of the resource, makes modifications, and then releases the lock. During this process, the server prevents other clients from acquiring a lock on the same resource. Relational databases operate in this manner.
- Optimistic Concurrency Control - In this model, the client first gets a token. Instead of obtaining a lock, the client attempts a write operation with the token included in the request. The operation succeeds if the token is still valid and fails otherwise.
Since HTTP is stateless, we can’t apply pessimistic concurrency control, and HTTP is designed for optimistic concurrency control.
How Optimistic Concurrency Control works in HTTP?
- Client sends the request to retrieve the state with the GET verb.
- Server sends the response along with the token in the ETag or Last-Modified header.
- Client sends the request to update the resource along with the received token (in the If-Match or If-Unmodified-Since header).
- Server checks whether the client supplied token is still valid. If it is not, then there is a concurrency failure, and the server aborts the request with 412 (Precondition Failed).
Example:
PUT /api/news/7455805 HTTP/1.1
Host: api.example.com
If-Match: "<etag received in the GET response>"
Content-Type: application/json
{ ...updated news article... }
HTTP/1.1 412 Precondition Failed
Must Do: It is mandatory to use optimistic concurrency control for PUT and DELETE operations. If you are using POST for resource state updates, then you should apply concurrency control for it as well.
Best practices checklist
Performance
- All API responses should contain the Cache-Control header with appropriate directives.
- Cache-Control should have clear information about cacheability, whether the response is cacheable or not.
- Cache policy should be defined clearly and separately for the client and the proxy.
- Use the proxy or CDN (in our case, Cloudflare page rules) to cache the API response.
- Should consider using an edge worker to cache POST responses, just in case POST is used to handle large queries or other read operations.
- Should use conditional requests when you can’t decide the stale time of a resource.
- Should use the ETag header to implement conditional requests.
- Conditional GET requests are only applicable to the GET method.
- Should enable compression for all API responses which have body content.
Concurrency
- Must use optimistic concurrency control for PUT and DELETE operations.
- Must use optimistic concurrency control for the POST operation when it is used for updating a resource.
Wrap up
In this article, we have looked at how to use the Cache-Control header, conditional GET with Last-Modified and ETag, compression, and optimistic concurrency control with conditional requests. I really appreciate that you took the time to read this article. In the next article, I will walk you through how to design long running requests, how to version an API without breaking the consumers, and how to test and document an API.
Related Posts
How to design resources and URIs for a REST API? - Part 2
Identify resources from domain nouns and functions, choose the right granularity with an example and follow the conventions to design URIs.
How to handle errors and secure a REST API? - Part 4
Classify errors and faults, design the error body and apply the security techniques for a REST API: authentication, CORS and rate limiting.
How to handle long running requests, versioning, testing and documentation in a REST API? - Part 6
Design long running requests with 202 and a status resource, define breaking changes and version an API, and cover testing and documentation with OpenAPI.