Smarter Cache Client

The django-redis client of Smarter’s caches, which stops waiting for a Redis that can’t be reached.

When Redis can’t be reached, the callers on a request’s path already do without the cache (issues #941, #1052, #1091). But each cache call first waits out a socket timeout, two seconds to connect or five for a command, and a request makes about 25 of them, one after another. While Redis drops packets, e.g. while its pod moves to another node, each request then takes minutes (issue #1096).

CircuitBreakerClient is django-redis’s DefaultClient with a circuit breaker for each Redis server, shared by every thread of the process:

  1. Closed. Every command goes to Redis. When one fails because Redis can’t be reached (a connection error or a timeout, see is_unreachable()), the breaker opens, and logs one warning line.

  2. Open. For CIRCUIT_BREAKER_SECONDS, every command fails at once, with no network round trip, raising the same ConnectionInterrupted as an outage does, so its callers degrade as they already do.

  3. Half open. After that, one command is let through to try Redis. If it succeeds, the breaker closes, and logs one line. If it fails, the breaker stays open for another interval. The other commands still fail at once while the trial is in flight.

An error that Redis answers with, e.g. a ResponseError for a wrong type, means that Redis can be reached, so it doesn’t open the breaker.

CACHE_OPTIONS in smarter.settings.base names this class as each cache’s CLIENT_CLASS, so every user of the default and sessions caches gets it: @cache_results, lazy_cache, waffle’s cache, the rate limits and the session store. Celery’s broker is usually the same server, and smarter.lib.celery_conf.publish.delay_through_breaker() queues a task through the same breaker, with CircuitBreaker.call().

class smarter.lib.cache.client.CircuitBreaker(name, open_seconds)[source]

Bases: object

The state of one Redis server, as seen by every thread of this process.

Parameters:
  • name (str) – What the log lines call the server, e.g. smarter-redis:6379. Never a url, which may hold a password.

  • open_seconds (float) – Seconds to fail fast after a failure, before one command may try Redis again.

__init__(name, open_seconds)[source]
allow()[source]

Decide whether a command may go to Redis now.

Return type:

bool

Returns:

True while the breaker is closed, and for the one command that tries Redis once it has been open for open_seconds. False for every other command while it is open.

call(command, open_error)[source]

Run a command that talks to this Redis server, unless the breaker is open.

Parameters:
Return type:

TypeVar(ResultType)

Returns:

The command’s result.

Raises:

BaseException – open_error() while the breaker is open, or whatever the command raised.

first_opened_at

When the outage began, for the line that closes the breaker.

property is_open: bool

Tell whether the breaker is open or half open.

Returns:

True if a command failed because Redis couldn’t be reached, and none has succeeded since.

opened_at

When the breaker last opened, by time.monotonic(), or None while it is closed.

record_error(error)[source]

Record what a command’s error says about Redis.

Parameters:

error (BaseException) – The error that the command raised.

Return type:

None

record_failure(error)[source]

Open the breaker, or keep it open for another interval, after a command couldn’t reach Redis.

Parameters:

error (BaseException) – The error of the command, for the line that opens the breaker.

Return type:

None

record_no_verdict()[source]

Let another command try Redis, after the trial failed before it could tell, e.g. while pickling a value.

Return type:

None

record_success()[source]

Close the breaker, if it was open, after a command reached Redis.

Return type:

None

trial_in_flight

Whether a command is trying Redis while the breaker is half open.

class smarter.lib.cache.client.CircuitBreakerClient(server, params, backend)[source]

Bases: DefaultClient

Django-redis’s DefaultClient, whose commands fail at once while Redis can’t be reached.

The breaker’s interval is the cache’s OPTIONS["CIRCUIT_BREAKER_SECONDS"], see smarter.settings.base.CACHE_CIRCUIT_BREAKER_SECONDS. See the module’s docstring for how the breaker works.

__init__(server, params, backend)[source]
add(key, value, timeout=<object object>, version=None, client=None)

Add a value to the cache, failing if the key already exists.

Returns True if the object was added, False if not.

Return type:

bool

property breaker: CircuitBreaker

Return the breaker of this cache’s Redis server, shared with every other client of the same server.

It is looked up on each command, rather than kept, so that reset_breakers(), after a fork or between tests, reaches the clients that already exist: Django keeps a cache client for each thread for as long as the thread lives.

Returns:

The breaker.

clear(client=None)

Flush all cache keys.

Return type:

None

decr(key, delta=1, version=None, client=None)

Decreace delta to value in the cache. If the key does not exist, raise a ValueError exception.

Return type:

int

delete(key, version=None, prefix=None, client=None)

Remove a key from the cache.

Return type:

int

delete_many(keys, version=None, client=None)

Remove multiple keys at once.

Return type:

int

delete_pattern(pattern, version=None, prefix=None, client=None, itersize=None)

Remove all keys matching pattern.

Return type:

int

expire(key, timeout, version=None, client=None)
Return type:

bool

expire_at(key, when, version=None, client=None)

Set an expire flag on a key to when, which can be represented as an integer indicating unix time or a Python datetime object.

Return type:

bool

get(key, default=None, version=None, client=None)

Retrieve a value from the cache.

Returns decoded value if key is found, the default if not.

Return type:

Any

get_many(keys, version=None, client=None)

Retrieve many keys.

Return type:

dict

has_key(key, version=None, client=None)

Test if key exists.

Return type:

bool

hdel(key, field, version=None, client=None)

Remove fields from hash key. Returns the number of fields deleted from the hash.

Return type:

int

hexists(key, field, version=None, client=None)

Return True if field exists in hash key, else False.

Return type:

bool

hkeys(key, version=None, client=None)

Return a list of fields in hash key.

Return type:

list[str]

hlen(key, version=None, client=None)

Return the number of items in hash key.

Return type:

int

hset(key, field=None, value=None, mapping=None, version=None, client=None)

Set the value of hash key at field to value. Returns the number of fields added to the hash.

Return type:

int

incr(key, delta=1, version=None, client=None, ignore_key_check=False)

Add delta to value in the cache. If the key does not exist, raise a ValueError exception. if ignore_key_check=True then the key will be created and set to the delta value by default.

Return type:

int

incr_version(key, delta=1, version=None, client=None)

Adds delta to the cache version for the supplied key. Returns the new version.

Return type:

int

keys(search, version=None, client=None)

Execute KEYS command and return matched results. Warning: this can return huge number of results, in this case, it strongly recommended use iter_keys for it.

Return type:

list[Any]

persist(key, version=None, client=None)
Return type:

bool

pexpire(key, timeout, version=None, client=None)
Return type:

bool

pexpire_at(key, when, version=None, client=None)

Set an expire flag on a key to when, which can be represented as an integer indicating unix time or a Python datetime object.

Return type:

bool

pttl(key, version=None, client=None)

Executes PTTL redis command and return the “time-to-live” of specified key. If key is a non volatile key, it returns None.

Return type:

int | None

sadd(key, *values, version=None, client=None)
Return type:

int

scard(key, version=None, client=None)
Return type:

int

sdiff(*keys, version=None, client=None)
Return type:

set[Any]

sdiffstore(dest, *keys, version_dest=None, version_keys=None, client=None)
Return type:

int

set(key, value, timeout=<object object>, version=None, client=None, nx=False, xx=False)

Persist a value to the cache, and set an optional expiration time.

Also supports optional nx parameter. If set to True - will use redis setnx instead of set.

Return type:

bool

set_many(data, timeout=<object object>, version=None, client=None)

Set a bunch of values in the cache at once from a dict of key/value pairs. This is much more efficient than calling set() multiple times.

If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.

Return type:

None

sinter(*keys, version=None, client=None)
Return type:

set[Any]

sinterstore(dest, *keys, version=None, client=None)
Return type:

int

sismember(key, member, version=None, client=None)
Return type:

bool

smembers(key, version=None, client=None)
Return type:

set[Any]

smismember(key, *members, version=None, client=None)
Return type:

list[bool]

smove(source, destination, member, version=None, client=None)
Return type:

bool

spop(key, count=None, version=None, client=None)
Return type:

set | Any

srandmember(key, count=None, version=None, client=None)
Return type:

list | Any

srem(key, *members, version=None, client=None)
Return type:

int

sscan(key, match=None, count=10, version=None, client=None)
Return type:

set[Any]

sunion(*keys, version=None, client=None)
Return type:

set[Any]

sunionstore(destination, *keys, version=None, client=None)
Return type:

int

touch(key, timeout=<object object>, version=None, client=None)

Sets a new expiration for a key.

Return type:

bool

ttl(key, version=None, client=None)

Executes TTL redis command and return the “time-to-live” of specified key. If key is a non volatile key, it returns None.

Return type:

int | None

zadd(key, mapping, nx=False, xx=False, ch=False, incr=False, gt=False, lt=False, version=None, client=None)

Add members with scores to sorted set.

Return type:

int | float | None

zcard(key, version=None, client=None)

Get the number of members in sorted set.

Return type:

int

zcount(key, min, max, version=None, client=None)

Count members in sorted set with scores between min and max.

Return type:

int

zincrby(key, amount, value, version=None, client=None)

Increment the score of member in sorted set by amount.

Return type:

float | None

zpopmax(key, count=None, version=None, client=None)

Remove and return members with highest scores.

Return type:

list[tuple[Any, float]] | tuple[Any, float] | None

zpopmin(key, count=None, version=None, client=None)

Remove and return members with lowest scores.

Return type:

list[tuple[Any, float]] | tuple[Any, float] | None

zrange(key, start, end, desc=False, withscores=False, score_cast_func=<class 'float'>, version=None, client=None)

Return members in sorted set by index range.

Return type:

list[Any] | list[tuple[Any, float]]

zrangebyscore(key, min, max, start=None, num=None, withscores=False, score_cast_func=<class 'float'>, version=None, client=None)

Return members in sorted set by score range.

Return type:

list[Any] | list[tuple[Any, float]]

zrank(key, value, withscore=False, version=None, client=None)

Get the rank (index) of member in sorted set, ordered low to high.

Return type:

int | list[Any] | None

zrem(key, *values, version=None, client=None)

Remove members from sorted set.

Return type:

int

zremrangebyscore(key, min, max, version=None, client=None)

Remove members from sorted set with scores between min and max.

Return type:

int

zrevrange(key, start, end, withscores=False, score_cast_func=<class 'float'>, version=None, client=None)

Return members in sorted set by index range, ordered high to low.

Return type:

list[Any] | list[tuple[Any, float]]

zrevrangebyscore(key, max, min, start=None, num=None, withscores=False, score_cast_func=<class 'float'>, version=None, client=None)

Return members in sorted set by score range, ordered high to low.

Return type:

list[Any] | list[tuple[Any, float]]

zscore(key, value, version=None, client=None)

Get the score of member in sorted set.

Return type:

float | None

smarter.lib.cache.client.DEFAULT_CIRCUIT_BREAKER_SECONDS = 5.0

Seconds that a breaker stays open, when the cache’s OPTIONS have no CIRCUIT_BREAKER_SECONDS.

smarter.lib.cache.client.GUARDED_COMMANDS: tuple[str, ...] = ('set', 'incr_version', 'add', 'get', 'persist', 'expire', 'pexpire', 'pexpire_at', 'expire_at', 'delete', 'delete_pattern', 'delete_many', 'clear', 'get_many', 'set_many', 'incr', 'decr', 'ttl', 'pttl', 'has_key', 'keys', 'sadd', 'scard', 'sdiff', 'sdiffstore', 'sinter', 'sinterstore', 'smismember', 'sismember', 'smembers', 'smove', 'spop', 'srandmember', 'srem', 'sscan', 'sunion', 'sunionstore', 'touch', 'hset', 'hdel', 'hlen', 'hkeys', 'hexists', 'zadd', 'zcard', 'zcount', 'zincrby', 'zpopmax', 'zpopmin', 'zrange', 'zrangebyscore', 'zrank', 'zrem', 'zremrangebyscore', 'zrevrange', 'zrevrangebyscore', 'zscore')

The DefaultClient methods that send a command to Redis, each of which goes through the breaker.

(
    'set',
    'incr_version',
    'add',
    'get',
    'persist',
    'expire',
    'pexpire',
    'pexpire_at',
    'expire_at',
    'delete',
    'delete_pattern',
    'delete_many',
    'clear',
    'get_many',
    'set_many',
    'incr',
    'decr',
    'ttl',
    'pttl',
    'has_key',
    'keys',
    'sadd',
    'scard',
    'sdiff',
    'sdiffstore',
    'sinter',
    'sinterstore',
    'smismember',
    'sismember',
    'smembers',
    'smove',
    'spop',
    'srandmember',
    'srem',
    'sscan',
    'sunion',
    'sunionstore',
    'touch',
    'hset',
    'hdel',
    'hlen',
    'hkeys',
    'hexists',
    'zadd',
    'zcard',
    'zcount',
    'zincrby',
    'zpopmax',
    'zpopmin',
    'zrange',
    'zrangebyscore',
    'zrank',
    'zrem',
    'zremrangebyscore',
    'zrevrange',
    'zrevrangebyscore',
    'zscore',
)
smarter.lib.cache.client.REDIS_ANSWERED_EXCEPTIONS: tuple[type[BaseException], ...] = (<class 'django_redis.exceptions.ConnectionInterrupted'>, <class 'redis.exceptions.RedisError'>)

Redis can be reached.

(
    <class 'django_redis.exceptions.ConnectionInterrupted'>,
    <class 'redis.exceptions.RedisError'>,
)
Type:

The other errors of a command, which Redis answered with, e.g. a ResponseError

smarter.lib.cache.client.UNGUARDED_COMMANDS: tuple[str, ...] = ('lock', 'iter_keys', 'sscan_iter')

The DefaultClient methods that reach Redis only later, and so bypass the breaker.

lock() returns a lock that talks to Redis when it is acquired, and the two *_iter() methods are generators that talk to Redis as they are iterated. Nothing on a request’s path uses them.

('lock', 'iter_keys', 'sscan_iter')
smarter.lib.cache.client.UNREACHABLE_EXCEPTIONS: tuple[type[BaseException], ...] = (<class 'redis.exceptions.ConnectionError'>, <class 'redis.exceptions.TimeoutError'>, <class 'TimeoutError'>, <class 'kombu.exceptions.OperationalError'>)

a refused or dropped connection, or a timeout.

Kombu raises OperationalError when it can’t publish a Celery task to the broker for want of a connection.

(
    <class 'redis.exceptions.ConnectionError'>,
    <class 'redis.exceptions.TimeoutError'>,
    <class 'TimeoutError'>,
    <class 'kombu.exceptions.OperationalError'>,
)
Type:

The errors that mean Redis can’t be reached

smarter.lib.cache.client.circuit_open_error()[source]

Return the error that a command raises at once while its breaker is open.

It is the error that django-redis raises during an outage, a ConnectionInterrupted caused by a redis-py ConnectionError. Django-redis’s cache re-raises the cause, so the callers that catch smarter.lib.cache.exceptions.CACHE_EXCEPTIONS catch it either way.

Return type:

ConnectionInterrupted

Returns:

The error.

smarter.lib.cache.client.get_breaker(location, open_seconds)[source]

Return the breaker of a Redis server, creating it on first use.

Parameters:
  • location (str) – The cache’s LOCATION, a Redis url.

  • open_seconds (float) – Seconds that a new breaker stays open after a failure.

Return type:

CircuitBreaker

Returns:

The breaker that every thread of this process shares for that server.

smarter.lib.cache.client.guarded(method)[source]

Wrap a DefaultClient command so that it goes through the client’s breaker.

Parameters:

method (TypeVar(CallableType, bound= Callable[..., Any])) – The command, e.g. DefaultClient.get.

Return type:

TypeVar(CallableType, bound= Callable[..., Any])

Returns:

The command, which raises circuit_open_error() at once while the breaker is open.

smarter.lib.cache.client.is_unreachable(error)[source]

Tell whether an error of a command means that Redis can’t be reached.

Libraries wrap redis-py’s errors: django-redis in ConnectionInterrupted, kombu, which publishes Celery’s tasks, in its OperationalError, each with the original error as its __cause__. So the error and its causes decide.

Parameters:

error (BaseException) – The error that a command raised.

Return type:

bool

Returns:

True for a connection error or a timeout, False for anything else, e.g. an error that Redis answered.

smarter.lib.cache.client.reset_breakers()[source]

Forget every breaker, e.g. in a process that was just forked, or between tests.

A forked process, such as a Celery worker’s child, starts with a copy of its parent’s breakers, whose locks may have been held at the moment of the fork.

Return type:

None

smarter.lib.cache.client.server_name(location)[source]

Return the name of a Redis server, from a cache’s LOCATION, without its credentials or database.

The default and sessions caches are two databases of one server, so they share one breaker.

Parameters:

location (str) – A Redis url, e.g. redis://user:password@smarter-redis:6379/1.

Return type:

str

Returns:

Its host and port, e.g. smarter-redis:6379, or a socket’s path.