Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep a shared data structure in-memory between Django Requests

My Django application is extremely performance sensitive and all requests require access to the same data structure. How do I store the data structure in such a way that it is accessible to all the requests?

Background:

I'm currently using the cache backend. This is a bit slow because the DS is large and it has to be retrieved and unpickled each time.

I understand that HTTP interactions should be stateless and knowingly need to break this constraint. Nothing bad should happen because it's read-only right?

like image 729
ldinh Avatar asked Sep 13 '13 21:09

ldinh


People also ask

What is default caching mechanism in Django?

Django has a default caching system in the form of local-memory caching. It is very powerful and robust. This system can handle multi-threaded processes and is efficient. It is best for those projects which cannot use Memcached framework.

How to use Redis in Django?

Django uses django-redis to execute commands in Redis. Looking at our example app in a text editor, we can see the Redis configuration in the settings.py file. We define a default cache with the CACHES setting, using a built-in django-redis cache as our backend.

How to store data in cache in Django?

To use cache in Django, first thing to do is to set up where the cache will stay. The cache framework offers different possibilities - cache can be saved in database, on file system or directly in memory. Setting is done in the settings.py file of your project.


2 Answers

There are a several ways to deal with this issue:

  1. Move the data structure out of Python completely (rather than loading it from a storage medium every time). For example, if your structure is conducive to it you could store it in Redis, MongoDB, Riak, or Neo4j. (As a bonus, you get the ability to query the data, if you need that ability).
  2. Move the structure to a separate process and communicate with it using a pipe or queue.
  3. Use a memory mapped file to share the data.

HTTP is stateless, but that doesn't mean that you can't preserve state between requests. You just have to do the work yourself (at the application level). The protocol doesn't do it for you. Ideally you avoid the state, as it makes it easier to scale horizontally, but not every application is easy to scale

like image 103
Sean Vieira Avatar answered Sep 25 '22 21:09

Sean Vieira


Django, and probably the majority of web applications, use caching. Of course the efficacy of caching depends on how you use it, i.e. by storing the data retrieved most frequently.

like image 25
Joseph Victor Zammit Avatar answered Sep 23 '22 21:09

Joseph Victor Zammit