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:
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.Open. For
CIRCUIT_BREAKER_SECONDS, every command fails at once, with no network round trip, raising the sameConnectionInterruptedas an outage does, so its callers degrade as they already do.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:
objectThe state of one Redis server, as seen by every thread of this process.
- Parameters:
- allow()[source]
Decide whether a command may go to Redis now.
- Return type:
- 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:
command (
Callable[[],TypeVar(ResultType)]) – The command, without arguments, e.g.functools.partial(task.delay, payload).open_error (
Callable[[],BaseException]) – Returns the error to raise at once while the breaker is open, e.g.circuit_open_error().
- 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:
- 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:
- 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:
- record_success()[source]
Close the breaker, if it was open, after a command reached Redis.
- Return type:
- 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:
DefaultClientDjango-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"], seesmarter.settings.base.CACHE_CIRCUIT_BREAKER_SECONDS. See the module’s docstring for how the breaker works.- add(key, value, timeout=<object object>, version=None, client=None)
Add a value to the cache, failing if the key already exists.
Returns
Trueif the object was added,Falseif not.- Return type:
- 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.
- 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:
- delete_pattern(pattern, version=None, prefix=None, client=None, itersize=None)
Remove all keys matching pattern.
- Return type:
- expire_at(key, when, version=None, client=None)
Set an expire flag on a
keytowhen, which can be represented as an integer indicating unix time or a Python datetime object.- Return type:
- 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:
- hdel(key, field, version=None, client=None)
Remove fields from hash key. Returns the number of fields deleted from the hash.
- Return type:
- hexists(key, field, version=None, client=None)
Return True if field exists in hash key, else False.
- Return type:
- 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:
- 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:
- 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:
- 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.
- pexpire_at(key, when, version=None, client=None)
Set an expire flag on a
keytowhen, which can be represented as an integer indicating unix time or a Python datetime object.- Return type:
- 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.
- 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:
- 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:
- touch(key, timeout=<object object>, version=None, client=None)
Sets a new expiration for a key.
- Return type:
- 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.
- 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.
- zcount(key, min, max, version=None, client=None)
Count members in sorted set with scores between min and max.
- Return type:
- zincrby(key, amount, value, version=None, client=None)
Increment the score of member in sorted set by amount.
- zpopmax(key, count=None, version=None, client=None)
Remove and return members with highest scores.
- zpopmin(key, count=None, version=None, client=None)
Remove and return members with lowest scores.
- 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.
- 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.
- zrank(key, value, withscore=False, version=None, client=None)
Get the rank (index) of member in sorted set, ordered low to high.
- zremrangebyscore(key, min, max, version=None, client=None)
Remove members from sorted set with scores between min and max.
- Return type:
- 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.
- 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.
- 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
DefaultClientmethods 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
DefaultClientmethods 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
OperationalErrorwhen 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
ConnectionInterruptedcaused by a redis-pyConnectionError. Django-redis’s cache re-raises the cause, so the callers that catchsmarter.lib.cache.exceptions.CACHE_EXCEPTIONScatch 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:
- Return type:
- Returns:
The breaker that every thread of this process shares for that server.
- smarter.lib.cache.client.guarded(method)[source]
Wrap a
DefaultClientcommand so that it goes through the client’s breaker.
- 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 itsOperationalError, 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:
- 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: