Skip to main content

Upstash Redis Python SDK

upstash-redis is a connectionless, HTTP-based Redis client for Python, designed to be used in serverless and serverful environments such as:

  • AWS Lambda
  • Vercel Serverless
  • Google Cloud Functions
  • and other environments where HTTP is preferred over TCP.

Inspired by other Redis clients like @upstash/redis and redis-py, the goal of this SDK is to provide a simple way to use Redis over the Upstash REST API.

The SDK is currently compatible with Python 3.8 and above.

Quick Start

Install

PyPI

pip install upstash-redis

Usage

To be able to use upstash-redis, you need to create a database on Upstash and grab UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN from the console.

# for sync client
from upstash_redis import Redis

redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN")

# for async client
from upstash_redis.asyncio import Redis

redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN")

Or, if you want to automatically load the credentials from the environment:

# for sync use
from upstash_redis import Redis
redis = Redis.from_env()

# for async use
from upstash_redis.asyncio import Redis
redis = Redis.from_env()

If you are in a serverless environment that allows it, it's recommended to initialise the client outside the request handler to be reused while your function is still hot.

Running commands might look like this:

from upstash_redis import Redis

redis = Redis.from_env()

def main():
  redis.set("a", "b")
  print(redis.get("a"))

# or for async context:

from upstash_redis.asyncio import Redis

redis = Redis.from_env()

async def main():  
  await redis.set("a", "b")
  print(await redis.get("a"))

BITFIELD and BITFIELD_RO

One particular case is represented by these two chained commands, which are available as functions that return an instance of the BITFIELD and, respectively, BITFIELD_RO classes. Use the execute function to run the commands.

redis.bitfield("test_key") \
  .incrby(encoding="i8", offset=100, increment=100) \
  .overflow("SAT") \
  .incrby(encoding="i8", offset=100, increment=100) \
  .execute()

redis.bitfield_ro("test_key_2") \
  .get(encoding="u8", offset=0) \
  .get(encoding="u8", offset="#1") \
  .execute()

Redis Streams

Redis Streams provide a powerful data structure for handling real-time data. The SDK supports all stream commands:

from upstash_redis import Redis

redis = Redis.from_env()

# Add entries to a stream
entry_id = redis.xadd("mystream", "*", {"field1": "value1", "field2": "value2"})
print(f"Added entry: {entry_id}")

# Read from stream
messages = redis.xread({"mystream": "0-0"})
print(f"Messages: {messages}")

# Create consumer group
redis.xgroup_create("mystream", "mygroup", "$")

# Read as part of consumer group  
messages = redis.xreadgroup("mygroup", "consumer1", {"mystream": ">"})

# Acknowledge processed messages
if messages:
    message_ids = [msg[0] for msg in messages[0][1]]
    redis.xack("mystream", "mygroup", *message_ids)

# Get stream length
length = redis.xlen("mystream")
print(f"Stream length: {length}")

For async usage:

from upstash_redis.asyncio import Redis

redis = Redis.from_env()

async def stream_example():
    # Add entries to a stream
    entry_id = await redis.xadd("mystream", "*", {"user": "alice", "action": "login"})
    
    # Read from stream
    messages = await redis.xread({"mystream": "0-0"})
    
    # Consumer group operations
    await redis.xgroup_create("mystream", "processors", "$")
    messages = await redis.xreadgroup("processors", "worker1", {"mystream": ">"})

Vector indexes

Store embeddings under IDs and run nearest-neighbour queries inside Redis (docs):

index = redis.vector.create_index(name="docs", dimension=3, metric="COSINE")
# or, for an existing index: index = redis.vector.index("docs")

index.add("doc-1", [0.1, 0.2, 0.3])  # a list of numbers, raw FP32 bytes or a base64 FP32 string

for match in index.query(vector=[0.1, 0.2, 0.3], top_k=5):
    print(match.id, match.score)  # scores are normalized to 0..1, higher is closer

index.get("doc-1")    # [0.1..., 0.2..., 0.3...] or None
index.count()         # 1
index.info()          # VectorIndexInfo(dimension=3, metric=<VectorMetric.COSINE: 'COSINE'>)
index.delete("doc-1")
index.drop()

Vector commands also work in pipelines and transactions through pipeline.vector.

Arrays

Sparse, index-addressed arrays (docs):

redis.arset("readings", 0, "21.5", "21.7")     # positional write, returns newly occupied slots
redis.arinsert("log", "boot", "ready")         # append, returns the index of the last value
redis.armget("readings", 0, 1)                 # ['21.5', '21.7']
redis.arscan("readings", 0, 1000)              # [(0, '21.5'), (1, '21.7')]
redis.argrep("log", "-", "+", match="boot")    # [0]
redis.arop("readings", 0, 1000, "SUM")         # 43.2
redis.arring("last-10", 10, "event")           # fixed-size ring buffer
redis.arlastitems("last-10", 10)               # most recent values, oldest first

Custom commands

If you want to run a command that hasn't been implemented, you can use the execute function of your client instance and pass the command as a list.

redis.execute(command=["XLEN", "test_stream"])

Pipelines & Transactions

If you want to submit commands in batches to reduce the number of roundtrips, you can utilize pipelining or transactions. The difference between pipelines and transactions is that transactions are atomic: no other command is executed during that transaction. In pipelines there is no such guarantee.

To use a pipeline, simply call the pipeline method:

pipeline = redis.pipeline()

pipeline.set("foo", 1)
pipeline.incr("foo")
pipeline.get("foo")

result = pipeline.exec()

print(result)
# prints [True, 2, '2']

For transaction, use mutli:

pipeline = redis.multi()

pipeline.set("foo", 1)
pipeline.incr("foo")
pipeline.get("foo")

result = pipeline.exec()

print(result)
# prints [True, 2, '2']

You can also chain the commands:

pipeline = redis.pipeline()

pipeline.set("foo", 1).incr("foo").get("foo")
result = pipeline.exec()

print(result)
# prints [True, 2, '2']

Telemetry

This library sends anonymous telemetry data to help us improve your experience. We collect the following:

  • SDK version
  • Platform (Vercel, AWS)
  • Python Runtime version
  • Retry count of retried requests (to measure retry rates)

You can opt out by passing allow_telemetry=False when initializing the Redis client:

redis = Redis(
  # ...,
  allow_telemetry=False,
)

Encoding

Although Redis can store invalid JSON data, there might be problems with the deserialization. To avoid this, the Upstash REST proxy is capable of encoding the data as base64 on the server and then sending it to the client to be decoded.

For very large data, this can add a few milliseconds in latency. So, if you're sure that your data is valid JSON, you can set rest_encoding to None.

Retry mechanism

upstash-redis has a fallback mechanism in case of network or API issues. By default, if a request fails it'll retry once, 3 seconds after the error. If you want to customize that, set rest_retries and rest_retry_interval (in seconds).

Contributing

Preparing the environment

This project uses Poetry for packaging and dependency management. Make sure you are able to create the poetry shell with relevant dependencies.

You will also need a database on Upstash.

Running tests

To run all the tests, make sure the poetry virtual environment activated with all the necessary dependencies. Set the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables and run:

poetry run pytest

Metadata

Release files for upstash-redis 1.9.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for upstash-redis 1.9.0
File Size Uploaded Provenance Actions
upstash_redis-1.9.0.tar.gz 55.0 kB Without provenance Details for upstash_redis-1.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for upstash-redis 1.9.0
File Interpreter ABI Platform Actions
upstash_redis-1.9.0-py3-none-any.whl Python 3 none any Details for upstash_redis-1.9.0-py3-none-any.whl

Total release size: 112.4 kB

Release files / upstash_redis-1.9.0.tar.gz

Download URL upstash_redis-1.9.0.tar.gz
Size 55.0 kB
Tags Source
SHA-256 checksum
How to use checksums
a970603791101271ad30eaa9e68de4678b653c09f373864188452c23938a9b19
BLAKE2b-256 checksum
How to use checksums
acd24ef68e114c499531b19199016480b0d439b62f8dfff047852123b90e9613
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.4 CPython/3.8.18 Linux/7.0.0-1017-azure

Release files / upstash_redis-1.9.0-py3-none-any.whl

Download URL upstash_redis-1.9.0-py3-none-any.whl
Size 57.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
81153171c427c13d454cc280b6a1d88f24ce25c82daee1d3ee64276d0558b20d
BLAKE2b-256 checksum
How to use checksums
5b5bf6e86474f3ad5ef11f4aed569dde87411eed46b2d02bf31afcc33a0e3cf5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.4 CPython/3.8.18 Linux/7.0.0-1017-azure

Security for upstash-redis 1.9.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page