skip to Main Content

I’m trying to speed up the home page of a website that queries the database for a random URL to use as the background image. One thing I have tried is to add a function to the Python code that caches the result of that database query for 60 minutes, and when I run the server locally I see that it seems to work correctly: reloading the page shows the same image as the previous time, instead of a new random image.

However when I deployed this code to a Digital Ocean droplet running an Apache server, it didn’t seem to work: reloading the page would show a different image. I suspect that what is happening is that different workers are handling my request each time, and each of these workers has its own cached result from the database.

Is there any way to cache these database queries across workers or achieve some similar result? Note: the obvious solution of hard-coding the background image is not an option, as the person for whom I am working wants the background image to vary.

2

Answers


  1. Chosen as BEST ANSWER

    After doing some more reading it seems the standard solution to this problem is to use a db query caching system like Memcached or Redis.


  2. Apache has shared memory between workers, but I’m not aware of anyway for python (say uwsgi) to access it. Same with nginx.

    Alternative would be to use an algorithm to determine what to display rather then being truly random. For example, all queries with hour == 1 -> picture_1, hour == 2 -> picture_2, etc.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search