Sometimes your application runs multiple queries that can get very expensive in terms of performance. There are many tools and options when it comes to performance-optimization, and one of them is called caching.
Caching refers to the process of storing data in a temporary location. When a request is made, system will first check this cached file to check if the data is available. It is very useful when the data is frequently accessed and/or the database is under high load.
One popular choice for such a database is Redis. It’s very popular to combine Django’s security features with Redis’s performance and scalability.
Redis is an in-memory data structure store that is commonly used as a cache and message broker.
Let’s say you have a social-network app that lets you share images and you want to store the view-count for each image.
As you can imagine, the number of requests (when visiting an image page) on the database can get very high very quickly (think thousands of users, each posting hundreds of images).
That’s when storing this data locally and caching it from the memory comes very handy.
With Django’s ORM, each time an image has been viewed you would have to make an additional SQL UPDATE
query. With Redis you can simply increment a counter stored locally.
|
|
incr()
Method increments given value by 1 (if it doesn’t exist, it will first create it). The convention for naming Redis keys is using colon sign as a separator for creating namespaced keys, e.g. object-type::id::field
.
This way you retrieve the requested data from a local memory file, making it a lot faster and saving your main database from additional unnecessary queries.
This is just a very simple example, and Redis offers many more tools.