Cache

Cache #

Avantages #

  • A cache system allows to reduce the number of requests as well as the resulting processing
  • Only necessary requests are processed
  • The principle of a cache system is to retrieve information (such as HTML code) and put it aside in a file (cached) so that the next time the page is executed, the information is displayed directly without redoing all the operations.
  • Reading a file is much faster than making a request.

Types #

  • CDN
  • Server Side
  • Client-Side
  • Cache in memory

Cache in memory #

  • Redis
    • Has different data types
    • Can be persisted on disk
    • Redis data keys and strings can be up to 512 MB (megabytes) in length
    • Supports replica by default
  • Memcached
    • Stores only strings
    • Can’t be persisted on disk
    • Supports a key of only 250 bytes and values are capped at 1MB by default
    • Does not support replication without third party software

filesystem

Terms #

  • Hit: The key is available in cache
  • Miss: The key isn’t available in cache
  • Invalidate
  • TTL: Time To Live
  • Eviction: Unecessary keys are evicted
    • FIFO
    • LRU: List recently used
    • LFU: List frequently used

Caching patterns #

Cashe-Aside #

Cache aside

  • Resilient to cache failures. If the cache cluster goes down, the system can still operate by going directly to the database.
  • Cache can be different than the data model in database

=> Use TTL to have updated data => Invalidate the cache entry if freshness must be guaranteed

Read-Through #

Read through

  • The fetching data logic is usually supported by the library or stand-alone cache provider
  • data model in read-through cache cannot be different than that of the database.

=> Warming or Pre-heating the cache by issuing queries manually to deal with cache miss when the data is requested for the first time

Write-Through #

Write through

We get all the benefits of read-through and we also get data consistency guarantee,

Write-Around #

data is written directly to the database and only the data that is read makes it way into the cache.

Write-Back #

The application writes data to the cache which acknowledges immediately and after some delay, it writes the data back to the database.

Write back

Cache ESI #

  • What if you cannot cache the whole page? What if you can cache everything but some sidebar that is more dynamic that the rest of the content? Edge Side Includes (ESI) to the rescue! Instead of generating the whole content in one go, ESI allows you to mark a region of a page as being the content of a sub-request call
  • For ESI to work, you need to use a reverse proxy that supports it like the Symfony implementation => Varnish is the best alternative

PHP #

It’s here