or why VCL is the best thing since sliced bread.
A lot of people like Varnish for it's speed. Myself, I am more and more fascinated by how much one can do in VCL and Inline C.
Let's say you have a paywall. In 2010 there was a lot of talks about putting paywalls around online newspapers. Usually it is believed that when you need to authenticate the user you cannot use Varnish or edge side caching. This is wrong. It just requires a bit of thinking and a bit of hackery. This is how it could be implemented:
A user with a valid account turns up on your website. Varnish looks for a session cookie but we can't find one. So we pass the request directly to a login page, called a validator from now on. The validator gets your username and password, checks them against a database and then, if they are correct, it sets a session cookie. The cookie contains a user ID and a expiration time set in the near future, 24 hours or so. The cookie itself can be set to expire in a month.
The validator signs this cookie with a shared secret using HMAC or a simple hash algorithm, all depending on the level of security your applying. After the cookie is set the user is then directed back to whatever content they originally requested.
Now, the client sends the request with the cookie back to Varnish. We recognize this is a session cookie in vcl_recv. With some inline C we now check the following:
- the expiration time is not yet reached. To avoid any parsing issues I suggest using an epoch integer for the expiry time.
- the signature is valid. Varnish must of course have access to the shared secret.
If the cookie passes these tests then we look the content up in the cache and deliver it to the user. As the 24 hours pass the second test will fail and we would need to re-validate the cookie. This is done easily by passing the request to the validating service on the backend. The validator checks if the cookie is indeed signed by it and that the user is still allowed to see the actual content. If so, the validator extend the expiration time in the cookie and re-sign it. Then we redirect the user back to the content. All this without having the user log in again.
Since the process of re-validating the cookies is relatively cheap one could set the expiration time in the cookie to just one hour or even less. Useful is your subscriptions are short.
Pretty cool, eh? If you want to actually implement this and need help, please get in touch with us.
Picture by Pink Sherbet Photography and used under a CC licence.