Going crazy with caching


Caching pages of logged in users


Bulgaria PHP Conference,
September 26th, 2015


© David Buchmann

HTTP Caching

What is a reverse proxy again?

VCL Hook Functions

Default Varnish behaviour

Default Varnish behaviour

Strategies when working with sessions

Avoid Sessions

Avoid Session

if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-3600);
}
            

Cleanup Cookies: Remove all but session cookie

sub vcl_recv {
    set req.http.cookie = ";" + req.http.cookie;
    set req.http.cookie = regsuball(req.http.cookie, "; +", ";");
    set req.http.cookie = regsuball(req.http.cookie, ";(PHPSESSID)=", "; \1=");
    set req.http.cookie = regsuball(req.http.cookie, ";[^ ][^;]*", "");
    set req.http.cookie = regsuball(req.http.cookie, "^[; ]+|[; ]+$", "");
    if (req.http.Cookie == "") {
        remove req.http.Cookie;
    }
}
            

varnish-cache.org/trac/wiki/VCLExampleRemovingSomeCookies #RemovingallBUTsomecookies

Cache lookup despite cookies

Cache lookup despite cookies

builtin.vcl

                // builtin.vcl
                sub vcl_recv {
                    // ...
                    if (req.method != "GET" && req.method != "HEAD") {
                        /* We only deal with GET and HEAD by default */
                        return (pass);
                    }
                    if (req.http.Authorization || req.http.Cookie) {
                        /* Not cacheable by default */
                        return (pass);
                    }

                    return (hash);
                }
            

Cache lookup despite cookies

                // default.vcl
                sub vcl_recv {
                    // ...
                    if (req.method != "GET" && req.method != "HEAD") {
                        /* We only deal with GET and HEAD by default */
                        return (pass);
                    }

                    return (hash);
                }
            

User Context

Introducing the User Context Hash

User Context