DIY Cache With xdataserver

I'd like to implement cache for speeding up frequently used slow endpoints.
Idea is that before endpoint execution I should check if cache data is valid (check latestest modified records in tables used) if cache is invalid go to original endpoint, otherwise return cached data as content.
After true execution (end point was actually called) save response as new cache.
I think that middleware are corrent way to do these but I couldn't figure how to determinate if it's called before or after execution.

Middleware ProcessRequest is always called before the next middleware. That's why you have to call Next, if you want the request to be forwarded to the next middleware in chain.