3

My Java application has REST GET apis (implemented with JAX-RS) that access MongoDB collection. I'm trying to introduce web cache to reduce response time (by reducing document read at MongoDB side).

I'm looking for standard way to provide ETag (http://en.wikipedia.org/wiki/HTTP_ETag) for resources(resources are derived from documents in MongoDB collection), so that ETag in MongoDB collection will be updated automatically every time document is updated.

Now, I can validate ETag in HTTP request ("If-None-Match") with ETag in MongoDB document, and if both are same return 304 (Not Modified). Now, WebCache can return already cached resource to client, thus improve response time.

While googling, I got following 2 options :

  1. hascode() as ETag : get document from MongoDB and populate Java object, then, calculate hashCode() which is used as ETag. But I want to avoid this overhead (full doc read + hashcode calculation) https://devcenter.heroku.com/articles/jax-rs-http-caching

  2. Last modified date as ETag: Add new field "Last modified" to mongoDB collection. http://howtodoinjava.com/2013/06/05/jax-rs-resteasy-cache-control-with-etag-example/ This mechanism is more suitable for "Last Modified" header (HTTP response). It looks, date is misused here for ETag. Here I've to modify existing doc to insert new field (updatedTime). Again, precision of HTML date is sec and mongoDB date is msec.

Please sugggest standard way to provide ETag in MongoDB.

1 Answer 1

0

I'm doing the hash code calculation before persisting the object in MongoDB, storing it in a field etag.

When receiving a request I can lookup {"_id": REQUESTED_ID, "etag": {$ne: RECEIVED_ETAG}}.

If no document is returned you may still need to find out if the document {"_id": REQUESTED_ID} exists (I do, but maybe in your case the WebCache can handle this and return 404, otherwise 304).

If it does return a document, just use its etag attribute to fill in the ETag header and probably remove it from the returned body.

Sign up to request clarification or add additional context in comments.

1 Comment

How do you cache queries? A query can return multiple documents.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.