Should a connection to Redis cluster be made on each Flask request?
<p>I have a Flask API, it connects to a Redis cluster for caching purposes. Should I be creating and tearing down a Redis connection on each flask api call? Or, should I try and maintain a connection across requests?</p>

<p>My argument against the second option is that I should really try and keep the api as stateless as possible, and I also don't know if keeping some persistent across request might causes threads race conditions or other side effects.</p>

<p>However, if I want to persist a connection, should it be saved on the session or on the application context?</p>

<p>This is about performance and scale. To get those 2 buzzwords buzzing you'll in fact need persistent connections.</p>

<p>Eventual race conditions will be no different than with a reconnect on every request so that shouldn't be a problem. Any RCs will depend on how you're using redis, but if it's just caching there's not much room for error.</p>

<p>I understand the desired stateless-ness of an API from a client sides POV, but not so sure what you mean about the server side.</p>

<p>I'd suggest you put them in the application context, not the sessions (those could become too numerous) whereas the app context gives you the optimal 1 connection per process (and created immediately at startup). Scaling this way becomes easy-peasy: you'll never have to worry about hitting the max connection counts on the redis box (and the less multiplexing the better).</p>

python flask redis