Optimize Your Rest Api With HTTP Multipart Batched Request
Sometimes api endpoints can receive too many requests because of their structure or we try to develop some other endpoints for handling such situations.
For example;
Imagine you are working on an admin panel has a dashboard interface. Actually you need an endpoint that provides last orders, last members, last added products, last comments etc.
How do we do this?
Way1:
We can send requests individually for each endpoint and collect responses. We sent 4 requests to 4 different endpoints for above scenario. Also all requests await completion of previous request to begin if requests are not async.
Result: 4 http-requests, 4 t response time.
I think this is the worst implementation.
Way2:
Maybe we can improve somethings. We can develop a special endpoint for these 4 requests. I think this way is better for performance but it is anti pattern. Because we may have broken the api standards if we do this.
Also development cost is too much. Because we should change the endpoint for every additional change.
One last thing; it is not smart that to create a new endpoint for every special requests.
Way3:
With advice of Sedat Sevgili I was informed about “HTTP Multipart Batch Request” and I tried to implement it. A method that allows main “HTTP Post” request that contains independent requests as can be understood this.
Main Idea:
Submitted batch request has a header that declare this request is a “multipart/batch” request. Additionally it has a boundary header that separates each request in batch request content.
All sub requests are placed as raw messages in batch requests body and separate by boundary.
A multipart/batch request sample:
Response of this request context contains sub responses for each sub request that separated by boundary like batch request body.
A multipart/batch response sample:
It’s up to you to decide how to interpretation of batch request.
We use “Symfony Framework” in our company so we use “Symfony” sub request to handle batch requests. Thus we handle all sub requests on HTTP Kernel layer without server request.
We developed a client that create http batch request and a “Symfony Bundle” that handle http batch requests.