TITLE: Basic Usage of Upstash Redis in TypeScript DESCRIPTION: This comprehensive example demonstrates how to initialize a Redis client and perform various Redis operations including string manipulation, sorted sets, lists, hashes, and sets. It covers key-value operations, expiration, and different data structures supported by Redis. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // string await redis.set('key', 'value'); let data = await redis.get('key'); console.log(data) await redis.set('key2', 'value2', {ex: 1}); // sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) data = await redis.zrange('scores', 0, 100 ) console.log(data) // list await redis.lpush('elements', 'magnesium') data = await redis.lrange('elements', 0, 100 ) console.log(data) // hash await redis.hset('people', {name: 'joe'}) data = await redis.hget('people', 'name' ) console.log(data) // sets await redis.sadd('animals', 'cat') data = await redis.spop('animals', 1) console.log(data) ---------------------------------------- TITLE: Implementing Leaderboard API with Cloudflare Workers and Upstash Redis DESCRIPTION: Complete JavaScript implementation for a leaderboard API using Cloudflare Workers and Upstash Redis. The code handles HTTP requests, provides endpoints for adding scores and retrieving the leaderboard, and implements edge caching for improved performance. LANGUAGE: javascript CODE: addEventListener("fetch", (event) => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { if (request.method === "GET") { return getLeaderboard(); } else if (request.method === "POST") { return addScore(request); } else { return new Response("Invalid Request!"); } } async function getLeaderboard() { let url = "https://us1-full-bug-31874.upstash.io/zrevrange/scores/0/1000/WITHSCORES/?_token=" + TOKEN; let res = await fetch(new Request(url), { cf: { cacheTtl: 10, cacheEverything: true, cacheKey: url, }, }); return res; } async function addScore(request) { const { searchParams } = new URL(request.url); let player = searchParams.get("player"); let score = searchParams.get("score"); let url = "https://us1-full-bug-31874.upstash.io/zadd/scores/" + score + "/" + player + "?_token=" + TOKEN; let res = await fetch(url); return new Response(await res.text()); } ---------------------------------------- TITLE: Retrieving a Value with Redis GET Command in Python DESCRIPTION: This example demonstrates how to use the Redis GET command to retrieve a value. It first sets a key-value pair with SET and then retrieves the value using GET, showing how to verify the retrieved value matches what was stored. LANGUAGE: python CODE: redis.set("key", "value") assert redis.get("key") == "value" ---------------------------------------- TITLE: Implementing Redis Transactions in TypeScript DESCRIPTION: Shows how to create and execute atomic transactions in Redis using the Upstash Redis SDK. Unlike pipelines, transactions ensure commands are executed sequentially without interruption. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.multi(); p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // execute the transaction const res = await p.exec<[Type1, Type2, Type3]>(); ---------------------------------------- TITLE: Implementing Express Session with Redis Store DESCRIPTION: This code demonstrates how to set up an Express application with Redis-based session storage using connect-redis. It initializes a Redis client, configures the session middleware with a Redis store, and creates routes that track and display page view counts for different paths. LANGUAGE: javascript CODE: var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(3000, function () { console.log("Example app listening on port 3000!"); }); ---------------------------------------- TITLE: Installing Serverless Framework DESCRIPTION: Command to install the Serverless Framework globally using npm. Version 3.39.0 is specified to ensure compatibility with the tutorial. LANGUAGE: shell CODE: npm i serverless@3.39.0 -g ---------------------------------------- TITLE: Incrementing Integer Value with Redis INCRBY Command in TypeScript DESCRIPTION: This example demonstrates how to use the Redis INCRBY command to increment the integer value of a key. It first sets a key to an initial value of 6, then increments it by 4, resulting in a final value of 10. LANGUAGE: typescript CODE: await redis.set("key", 6); await redis.incrby("key", 4); // returns 10 ---------------------------------------- TITLE: Setting Key Expiration in Redis using TypeScript DESCRIPTION: Example showing how to set a value with set() and then configure it to expire after 10 seconds using expire(). The expire command returns 1 if successful or 0 if the key doesn't exist. LANGUAGE: typescript CODE: await redis.set("mykey", "Hello"); await redis.expire("mykey", 10); ---------------------------------------- TITLE: Implementing Express Server with Redis Session Management DESCRIPTION: Complete Express.js application that demonstrates session management with Redis. The code connects to Upstash Redis, configures session middleware, and tracks page views for different routes. LANGUAGE: javascript CODE: var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/", function (req, res, next) { res.send("you viewed this page " + req.session.views["/"] + " times"); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(8080, function () { console.log("Example app listening on port 8080!"); }); ---------------------------------------- TITLE: Connecting to Upstash Redis using redis-cli DESCRIPTION: This snippet demonstrates how to connect to an Upstash Redis database using redis-cli and execute basic commands such as set, get, and incr. It shows the connection parameters needed including TLS, password, endpoint, and port. LANGUAGE: bash CODE: > redis-cli --tls -a PASSWORD -h ENDPOINT -p PORT ENDPOINT:PORT> set counter 0 OK ENDPOINT:PORT> get counter "0" ENDPOINT:PORT> incr counter (int) 1 ENDPOINT:PORT> incr counter (int) 2 ---------------------------------------- TITLE: Initializing Upstash Redis Client from Environment Variables in Python DESCRIPTION: Code snippet demonstrating how to initialize both synchronous and asynchronous Redis clients by loading credentials automatically from environment variables. LANGUAGE: python CODE: # 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() ---------------------------------------- TITLE: Implementing Redis Counter in Next.js Page DESCRIPTION: Next.js page component implementation that creates a counter using Redis for state management. Uses the Upstash Redis client to increment and retrieve the counter value. LANGUAGE: tsx CODE: import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ---------------------------------------- TITLE: Sample Response from Autocomplete API DESCRIPTION: Example JSON response from the autocomplete API when queried with the term 'ca'. LANGUAGE: json CODE: { "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true }, "body": "{\"message\":\"Query:ca\",\"result\":[\"CAMBODIA\",\"CAMEROON\",\"CANADA\",\"CAPE VERDE\",\"CAYMAN ISLANDS\"]}" } ---------------------------------------- TITLE: Popping Multiple Elements from Redis List using LPOP DESCRIPTION: Shows how to remove and return multiple elements from the beginning of a Redis list by specifying a count parameter. First pushes elements to the list using RPUSH, then removes two elements using LPOP. LANGUAGE: typescript CODE: await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key", 2); console.log(element); // ["a", "b"] ---------------------------------------- TITLE: Implementing Session Management in FastAPI with Upstash Redis DESCRIPTION: FastAPI application code that handles login, profile access, and logout using Redis for session management. It includes sliding expiration and cookie-based session handling. LANGUAGE: python CODE: from fastapi import FastAPI, Response, Cookie, HTTPException from pydantic import BaseModel from upstash_redis import Redis from dotenv import load_dotenv import uuid # Load environment variables load_dotenv() redis = Redis.from_env() app = FastAPI() SESSION_TIMEOUT_SECONDS = 900 # 15 minutes # Define the request body model for login class LoginRequest(BaseModel): username: str @app.post("/login/") async def login(request: LoginRequest, response: Response): session_id = str(uuid.uuid4()) redis.hset(f"session:{session_id}", values={"user": request.username, "status": "active"}) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) response.set_cookie(key="session_id", value=session_id, httponly=True) return {"message": "Logged in successfully", "session_id": session_id} @app.get("/profile/") async def get_profile(session_id: str = Cookie(None)): if not session_id: raise HTTPException(status_code=403, detail="No session cookie found") session_data = redis.hgetall(f"session:{session_id}") if not session_data: response = Response() response.delete_cookie(key="session_id") # Clear the expired cookie raise HTTPException(status_code=404, detail="Session expired") # Update the session expiration time (sliding expiration) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) return {"session_id": session_id, "session_data": session_data} @app.post("/logout/") async def logout(response: Response, session_id: str = Cookie(None)): if session_id: redis.delete(f"session:{session_id}") response.delete_cookie(key="session_id") return {"message": "Logged out successfully"} ---------------------------------------- TITLE: Running the Flask Application DESCRIPTION: Command to start the Flask development server and run the application locally. LANGUAGE: shell CODE: python app.py ---------------------------------------- TITLE: Retrieving Multiple Keys with MGET in Redis (TypeScript) DESCRIPTION: Demonstrates how to use the MGET command to load multiple keys at once from Redis. This operation counts as a single command for billing purposes. If a key is not found, it will be returned as null in the response array. LANGUAGE: typescript CODE: const values = await redis.mget("key1", "key2", "key3"); ---------------------------------------- TITLE: Implementing Multi-Region Rate Limiting with Upstash Redis in TypeScript DESCRIPTION: This code shows how to set up multi-region rate limiting using multiple Redis instances. It provides lower latencies for global users by replicating state across multiple databases using CRDTs. LANGUAGE: typescript CODE: import { MultiRegionRatelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }), new Redis({ /* auth */ }), ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), analytics: true, }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); ---------------------------------------- TITLE: Implementing Redis Counter in Next.js App Router DESCRIPTION: Next.js page component implementation using Upstash Redis to create a simple counter that increments on each page load. LANGUAGE: tsx CODE: import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ---------------------------------------- TITLE: Checking Set Membership with SISMEMBER in TypeScript DESCRIPTION: This example demonstrates how to check if a value exists in a Redis set. It first adds multiple members to a set named 'set', then uses sismember to check if 'a' is a member of the set, which returns 1 indicating the member exists. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const isMember = await redis.sismember("set", "a"); console.log(isMember); // 1 ---------------------------------------- TITLE: FastAPI Weather Cache Implementation DESCRIPTION: Main application code implementing a weather API endpoint with Redis caching. Includes Redis connection setup, cache checking, and external API integration with a 10-minute TTL for cached data. LANGUAGE: python CODE: from fastapi import FastAPI from upstash_redis import Redis import requests import os app = FastAPI() # Connect to Redis using environment variables redis = Redis.from_env() # Mock API endpoint for weather data WEATHER_API_URL = "https://api.weatherapi.com/v1/current.json" API_KEY = os.getenv("WEATHER_API_KEY") @app.get("/weather/{city}") def get_weather(city: str): cache_key = f"weather:{city}" # Check if the data exists in cache cached_data = redis.get(cache_key) if cached_data: return {"source": "cache", "data": cached_data} # Fetch data from external API response = requests.get(f"{WEATHER_API_URL}?key={API_KEY}&q={city}") weather_data = response.json() # Store the data in Redis cache with a 10-minute expiration redis.setex(cache_key, 600, weather_data) return {"source": "api", "data": weather_data} ---------------------------------------- TITLE: Adding Redis Client Dependency to Maven DESCRIPTION: XML snippet showing how to add the Jedis Redis client library as a dependency in the Maven pom.xml file. Jedis version 3.6.0 is specified. LANGUAGE: xml CODE: ... redis.clients jedis 3.6.0 ... ---------------------------------------- TITLE: Implementing Main Page Functionality in Next.js DESCRIPTION: This code snippet shows the main React component for the roadmap voting app. It includes methods for refreshing data, voting on features, adding new features, and handling email subscriptions. LANGUAGE: javascript CODE: import Head from 'next/head' import { ToastContainer, toast } from 'react-toastify'; import * as React from "react"; class Home extends React.Component { ... refreshData() { fetch("api/list") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.body }); this.inputNewFeature.current.value = ""; }, (error) => { this.setState({ isLoaded: true, error }); } ) } vote(event, title) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"title": title}) }; console.log(requestOptions); fetch('api/vote', requestOptions) .then(response => response.json()).then(data => { console.log(data) if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 3000}); } else { this.refreshData() } }) } handleNewFeature(event) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"title": this.inputNewFeature.current.value}) }; fetch('api/create', requestOptions) .then(response => response.json()).then(data => { if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 5000}); } else { toast.info("Your feature has been added to the list.", {hideProgressBar: true, autoClose: 3000}); this.refreshData() } }); event.preventDefault(); } handleNewEmail(event) { const requestOptions = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({"email": this.inputEmail.current.value}) }; console.log(requestOptions); fetch('api/addemail', requestOptions) .then(response => response.json()).then(data => { if(data.error) { toast.error(data.error, {hideProgressBar: true, autoClose: 3000}); } else { toast.info("Your email has been added to the list.", {hideProgressBar: true, autoClose: 3000}); this.refreshData() } }); event.preventDefault(); } } export default Home; ---------------------------------------- TITLE: Exchanging OAuth 2.0 Code for Access Token using cURL DESCRIPTION: This cURL command demonstrates how to exchange the OAuth 2.0 authorization code for an access token. It includes necessary parameters such as grant type, audience, client ID, code, and redirect URI. LANGUAGE: bash CODE: curl -XPOST 'https://auth.upstash.com/oauth/token' \ --header 'content-type: application/x-www-form-urlencoded' \ --data 'grant_type=authorization_code --data audience=upstash-api' \ --data 'client_id=XXXXXXXXXXX' \ --data 'code=XXXXXXXXXXXX' \ --data 'redirect_uri=localhost:3000' ---------------------------------------- TITLE: URL Shortener Implementation with Redis in Python DESCRIPTION: Complete Python implementation of a URL shortener that generates short codes, stores URLs in Redis with expiration times, and retrieves original URLs from short codes. LANGUAGE: py CODE: import string import random from upstash_redis import Redis from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Redis connection redis = Redis.from_env() # Characters to generate the short URL from CHARS = string.ascii_letters + string.digits BASE_URL = "https://short.url/" # Function to generate a random string for the short URL def generate_short_code(length=6): return ''.join(random.choices(CHARS, k=length)) # Function to shorten the URL with an expiration time def shorten_url(url, expiration=3600): # Generate a random short code short_code = generate_short_code() # Save the short code in Redis redis.set(short_code, url, ex=expiration) return BASE_URL + short_code # Function to get the original URL from the short URL def get_original_url(short_code): return redis.get(short_code) # Example usage if __name__ == "__main__": original_url = "https://example.com/my-very-long-url" # Shorten the URL short_url = shorten_url(original_url, expiration=600) print(f"Shortened URL: {short_url}") # Get the original URL original_url = get_original_url(short_url.split("/")[-1]) if original_url: print(f"Original URL: {original_url}") else: print("Short URL expired or not found") ---------------------------------------- TITLE: Implementing Redis Counter Handler in Java DESCRIPTION: Java implementation of the AWS Lambda request handler that connects to Upstash Redis, increments a counter value, and returns it in the HTTP response. The code uses Jedis client to interact with Redis. LANGUAGE: java CODE: package com.serverless; import java.util.Map; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import redis.clients.jedis.Jedis; public class Handler implements RequestHandler, ApiGatewayResponse> { @Override public ApiGatewayResponse handleRequest(Map input, Context context) { Jedis jedis = new Jedis("lasting-roughy-29092.upstash.io", 6379, true); jedis.auth("********"); Long value = jedis.incr("counter"); jedis.close(); String message = "Hello World, Count:" + value; return ApiGatewayResponse.builder() .setStatusCode(200) .setObjectBody(message) .build(); } } ---------------------------------------- TITLE: Incrementing Integer Value with Redis INCR Command in Python DESCRIPTION: Demonstrates how to increment a numeric value stored in Redis using the INCR command. The example first sets a key with value 6 and then increments it to 7. If the key doesn't exist, it will be initialized as 0 before incrementing. LANGUAGE: python CODE: redis.set("key", 6) assert redis.incr("key") == 7 ---------------------------------------- TITLE: Connecting with redis-py in Python DESCRIPTION: Example of connecting to Upstash Redis using the redis-py client library in Python, showing basic Redis operations with SSL enabled. LANGUAGE: python CODE: import redis r = redis.Redis( host= 'YOUR_ENDPOINT', port= 'YOUR_PORT', password= 'YOUR_PASSWORD', ssl=True) r.set('foo','bar') print(r.get('foo')) ---------------------------------------- TITLE: Initializing Ratelimit Client with Protection Enabled in TypeScript DESCRIPTION: This snippet shows how to create a new Ratelimit instance with protection enabled. It sets up a sliding window rate limit of 10 requests per 10 seconds and enables analytics. LANGUAGE: typescript CODE: const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), enableProtection: true analytics: true, }); ---------------------------------------- TITLE: Importing Upstash Redis in Deno DESCRIPTION: This snippet shows how to import the Redis class from the @upstash/redis package using Deno's import syntax. LANGUAGE: typescript CODE: import { Redis } from "https://deno.land/x/upstash_redis/mod.ts"; ---------------------------------------- TITLE: Configuring Upstash Ratelimit Strapi Plugin in JavaScript DESCRIPTION: JavaScript configuration for the Upstash Ratelimit Strapi plugin. This setup is similar to the TypeScript version, enabling the plugin, setting Redis credentials, and defining rate limiting strategies for API routes. LANGUAGE: javascript CODE: module.exports = () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s", }, }, ], prefix: "@strapi", }, }, }); ---------------------------------------- TITLE: Connecting to Upstash Redis with Redisson Client DESCRIPTION: This code sample demonstrates how to connect to an Upstash Redis database using the Redisson client. It configures the connection with the appropriate endpoint and password, creates a map in Redis, and performs basic put and get operations. LANGUAGE: typescript CODE: public class Main { public static void main(String[] args) { Config config = new Config(); config.useSingleServer().setPassword("YOUR_PASSWORD") // use "rediss://" for SSL connection .setAddress("YOUR_ENDPOINT"); RedissonClient redisson = Redisson.create(config); RMap map = redisson.getMap("map"); map.put("foo", "bar"); System.out.println(map.get("foo")); } } ---------------------------------------- TITLE: Retrieving Old Values While Setting Keys in Redis DESCRIPTION: This example shows how to use the get parameter to retrieve the old value of a key while setting a new value in a single operation. LANGUAGE: python CODE: # Get the old value stored at the key. assert redis.set("key", "new-value", get=True) == "old-value" ---------------------------------------- TITLE: Implementing Autocomplete API Handler in Node.js DESCRIPTION: JavaScript code for the Lambda function handler implementing the autocomplete API using Redis sorted sets. LANGUAGE: javascript CODE: var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis(process.env.REDIS_URL); } const headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true, }; module.exports.query = async (event, context, callback) => { if (!event.queryStringParameters || !event.queryStringParameters.term) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Term needed as query param.", }), }; } let term = event.queryStringParameters.term.toUpperCase(); let res = []; let rank = await client.zrank("terms", term); if (rank != null) { let temp = await client.zrange("terms", rank, rank + 100); for (const el of temp) { if (!el.startsWith(term)) { break; } if (el.endsWith("*")) { res.push(el.substring(0, el.length - 1)); } } } return { statusCode: 200, headers: headers, body: JSON.stringify({ message: "Query:" + event.queryStringParameters.term, result: res, }), }; }; ---------------------------------------- TITLE: Initializing Redis Client in Deno DESCRIPTION: Demonstrates how to initialize an Upstash Redis client in Deno environments such as Deno Deploy or Netlify Edge. Supports both direct configuration and loading from environment variables. LANGUAGE: typescript CODE: import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = new Redis({ url: , token: , }) // or const redis = Redis.fromEnv(); ---------------------------------------- TITLE: Sending JSON or Binary Values in POST Request Body DESCRIPTION: Example of sending a value in the request body of a POST request to the Upstash REST API. This allows sending complex values that would be difficult to encode in a URL. LANGUAGE: shell CODE: curl -X POST -d '$VALUE' https://us1-merry-cat-32748.upstash.io/set/foo \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ---------------------------------------- TITLE: Mixed Algorithm Rate Limiting Configuration DESCRIPTION: Advanced configuration demonstrating multiple rate limit strategies using different algorithms for specific routes. Combines fixed-window and token-bucket algorithms with custom header-based identification. LANGUAGE: json CODE: { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "/api/restaurants/:id", "identifierSource": "header.x-author", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } }, { "methods": ["GET"], "path": "/api/restaurants", "identifierSource": "header.x-author", "limiter": { "algorithm": "tokenBucket", "tokens": 10, "window": "20s", "refillRate": 1 } } ], "prefix": "@strapi" } } } ---------------------------------------- TITLE: Using Upstash Rate Limit SDK in a JavaScript Function DESCRIPTION: This snippet illustrates how to use the configured rate limiter in a JavaScript function. It checks if the request is allowed based on the IP address and returns appropriate responses. LANGUAGE: javascript CODE: export default async function handler(request) { const ip = request.ip ?? "127.0.0.1" const { success } = await ratelimit.limit(ip) return success ? new Response("OK") : new Response("Rate limit exceeded", { status: 429 }) } ---------------------------------------- TITLE: Using Custom Rates for Batch Processing in TypeScript DESCRIPTION: This snippet demonstrates how to use custom rates for rate limiting when processing batches of inputs. It allows subtracting a specific number from the available tokens based on the batch size. LANGUAGE: typescript CODE: const { success } = await ratelimit.limit("identifier", { rate: batchSize }); ---------------------------------------- TITLE: Popping Single Element from Redis List with LPOP in Python DESCRIPTION: This example demonstrates how to remove and return the first element from a Redis list using the LPOP command. It first pushes three elements to a list with RPUSH, then pops the first element with LPOP. LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.lpop("mylist") == "one" ---------------------------------------- TITLE: Implementing Token Bucket Rate Limiting with Redis - Regional DESCRIPTION: Creates a token bucket rate limiter that refills 5 tokens every 10 seconds with a maximum bucket size of 10 tokens. LANGUAGE: typescript CODE: const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.tokenBucket(5, "10 s", 10), analytics: true, }); ---------------------------------------- TITLE: Implementing a Redis Counter in Google Cloud Functions DESCRIPTION: This code snippet shows how to implement a serverless HTTP function that increments a counter in Redis each time the endpoint is called and returns the current count. It uses the Upstash Redis client to connect to a Redis instance using environment variables. LANGUAGE: js CODE: const { Redis } = require("@upstash/redis"); const functions = require('@google-cloud/functions-framework'); const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); functions.http('counter', async (req, res) => { const count = await redis.incr("counter"); res.send("Counter:" + count); }); ---------------------------------------- TITLE: Creating Next.js App and Installing Dependencies DESCRIPTION: Commands to create a new Next.js application with Pages Router and install the @upstash/redis package. LANGUAGE: shell CODE: npx create-next-app@latest cd my-app npm install @upstash/redis ---------------------------------------- TITLE: SST Configuration Setup DESCRIPTION: Configuration file for SST that sets up the Next.js application with environment variables for Upstash Redis LANGUAGE: typescript CODE: /// export default $config({ app(input) { return { name: "my-app", removal: input?.stage === "production" ? "retain" : "remove", home: "aws", }; }, async run() { new sst.aws.Nextjs("MyWeb", { environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || "", UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || "", }, }); }, }); ---------------------------------------- TITLE: Implementing Redis Counter with Google Cloud Functions in JavaScript DESCRIPTION: This code snippet sets up a Google Cloud Function that increments a Redis counter and returns the current count. It uses the @upstash/redis library to interact with an Upstash Redis database. LANGUAGE: javascript CODE: const { Redis } = require("@upstash/redis"); const functions = require('@google-cloud/functions-framework'); const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); functions.http('counter', async (req, res) => { const count = await redis.incr("counter"); res.send("Counter:" + count); }); ---------------------------------------- TITLE: Creating package.json with Upstash Dependencies DESCRIPTION: JSON configuration file that specifies the dependencies needed for the project, including @upstash/ratelimit and @upstash/redis packages. LANGUAGE: json CODE: { "dependencies": { "@upstash/ratelimit": "latest", "@upstash/redis": "latest" } } ---------------------------------------- TITLE: Simple ZUNIONSTORE Operation in TypeScript DESCRIPTION: Demonstrates a basic usage of the ZUNIONSTORE command to combine two sorted sets and store the result in a new key. It first adds members to two separate sets, then performs the union operation. LANGUAGE: typescript CODE: await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore("destination", 2, ["key1", "key2"]); console.log(res) // 2 ---------------------------------------- TITLE: Connecting with ioredis in Node.js DESCRIPTION: Example of connecting to Upstash Redis using the ioredis client library in Node.js, demonstrating basic set and get operations. LANGUAGE: javascript CODE: const Redis = require("ioredis"); let client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); await client.set("foo", "bar"); let x = await client.get("foo"); console.log(x); ---------------------------------------- TITLE: Implementing Rate Limiting in a FastAPI Application DESCRIPTION: Complete Python code for a FastAPI application with rate limiting using Upstash Redis. The application limits requests to 10 per 10 seconds using a Fixed Window rate limiter. LANGUAGE: python CODE: from fastapi import FastAPI, HTTPException from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis from dotenv import load_dotenv import requests # Load environment variables from .env file load_dotenv() # Initialize the FastAPI app app = FastAPI() # Initialize Redis client redis = Redis.from_env() # Create a rate limiter that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=redis, limiter=FixedWindow(max_requests=10, window=10), # 10 requests per 10 seconds prefix="@upstash/ratelimit" ) @app.get("/expensive_calculation") def expensive_calculation(): identifier = "api" # Common identifier for rate limiting all users equally response = ratelimit.limit(identifier) if not response.allowed: raise HTTPException(status_code=429, detail="Rate limit exceeded. Please try again later.") # Placeholder for a resource-intensive operation result = do_expensive_calculation() return {"message": "Here is your result", "result": result} # Simulated function for an expensive calculation def do_expensive_calculation(): return "Expensive calculation result" # Test function to check rate limiting def test_rate_limiting(): url = "http://127.0.0.1:8000/expensive_calculation" success_count = 0 fail_count = 0 # Attempt 15 requests in quick succession for i in range(15): response = requests.get(url) if response.status_code == 200: success_count += 1 print(f"Request {i+1}: Success - {response.json()['message']}") elif response.status_code == 429: fail_count += 1 print(f"Request {i+1}: Failed - Rate limit exceeded") # Small delay to avoid flooding print("\nTest Summary:") print(f"Total Successful Requests: {success_count}") print(f"Total Failed Requests due to Rate Limit: {fail_count}") if __name__ == "__main__": # Run the FastAPI app in a separate thread or terminal with: # uvicorn main:app --reload # To test rate limiting after the server is running test_rate_limiting() ---------------------------------------- TITLE: Implementing Lambda Function with Upstash Redis DESCRIPTION: Defines a Python Lambda function that increments a counter using Upstash Redis and returns the current count. LANGUAGE: python CODE: from upstash_redis import Redis redis = Redis.from_env() def handler(event, context): count = redis.incr('counter') return { 'statusCode': 200, 'body': f'Counter: {count}' } ---------------------------------------- TITLE: Scanning Redis Set Members with Pattern Matching in TypeScript DESCRIPTION: Demonstrates how to use SSCAN to iterate over a Redis set, adding members first with SADD and then scanning with a pattern match filter. Shows cursor-based iteration and pattern matching to filter members starting with 'a'. LANGUAGE: typescript CODE: await redis.sadd("key", "a", "ab","b", "c"); const [newCursor, fields] = await redis.sscan("key", 0, { match: "a*"}); console.log(newCursor); // likely `0` since this is a very small set console.log(fields); // ["a", "ab"] ---------------------------------------- TITLE: Implementing Stateful Server with Node.js and Redis DESCRIPTION: Node.js server code that uses ioredis to increment a counter in Redis and return the page view count. It listens on port 8080 and connects to Redis using an environment variable. LANGUAGE: javascript CODE: var Redis = require("ioredis"); const http = require("http"); if (typeof client === "undefined") { var client = new Redis(process.env.REDIS_URL); } const requestListener = async function (req, res) { if (req.url !== "/favicon.ico") { let count = await client.incr("counter"); res.writeHead(200); res.end("Page view:" + count); } }; const server = http.createServer(requestListener); server.listen(8080); ---------------------------------------- TITLE: Implementing Feature Listing API in Next.js DESCRIPTION: This serverless API function connects to Redis and fetches feature requests ordered by their scores (votes) from the Sorted Set 'roadmap'. LANGUAGE: javascript CODE: import { fixUrl } from "./utils"; import Redis from "ioredis"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); let n = await redis.zrevrange("roadmap", 0, 100, "WITHSCORES"); let result = []; for (let i = 0; i < n.length - 1; i += 2) { let item = {}; item["title"] = n[i]; item["score"] = n[i + 1]; result.push(item); } redis.quit(); res.json({ body: result, }); }; ---------------------------------------- TITLE: Implementing Redis Pipeline Commands in TypeScript DESCRIPTION: Demonstrates how to create and execute a pipeline of Redis commands using the Upstash Redis SDK. Shows both individual command chaining and inline command execution, with support for typed responses. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.pipeline(); // Now you can chain multiple commands to create your pipeline: p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // Execute the pipeline once you are done building it: // `exec` returns an array where each element represents the response of a command in the pipeline. // You can optionally provide a type like this to get a typed response. const res = await p.exec<[Type1, Type2, Type3]>(); ---------------------------------------- TITLE: Implementing Fixed Window Rate Limiting with Redis - Multi Regional DESCRIPTION: Creates a rate limiter that allows 10 requests per 10 seconds using the fixed window algorithm with multi-regional Redis setup. LANGUAGE: typescript CODE: const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"), }); ---------------------------------------- TITLE: Checking Multiple Set Members with Redis SMISMEMBER Command in TypeScript DESCRIPTION: This example demonstrates how to use the SMISMEMBER Redis command to check if multiple values exist in a set. First, it adds three elements to a set using SADD, then checks for the existence of three values (two that exist and one that doesn't), returning an array of binary values where 1 indicates membership and 0 indicates non-membership. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const members = await redis.smismember("set", ["a", "b", "d"]); console.log(members); // [1, 1, 0] ---------------------------------------- TITLE: Implementing Redis Increment Endpoint DESCRIPTION: Server-side API endpoint implementation that increments a counter and tracks last call time using Upstash Redis LANGUAGE: javascript CODE: import { defineEventHandler } from "h3"; import { Redis } from "@upstash/redis"; // Initialize Redis const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL || "", token: process.env.UPSTASH_REDIS_REST_TOKEN || "" }); export default defineEventHandler(async () => { const identifier = "api_call_counter"; try { // Increment the API call counter and get the updated value const count = await redis.incr(identifier); // Optionally, you can also retrieve other information like the last time it was called const lastCalled = await redis.get("last_called"); const lastCalledAt = lastCalled || "Never"; // Store the current timestamp as the last called time await redis.set("last_called", new Date().toISOString()); // Return the count and last called time return { success: true, count: count, lastCalled: lastCalledAt, }; } catch (error) { console.error("Redis error:", error); return { success: false, message: "Error interacting with Redis", }; } }); ---------------------------------------- TITLE: Implementing rate limiting with Upstash in Python DESCRIPTION: This snippet demonstrates how to create and use a rate limiter with Upstash Redis. It sets up a limit of 10 requests per 10 seconds and shows how to check if a request is allowed. LANGUAGE: python CODE: from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), # Optional prefix for the keys used in Redis. This is useful # if you want to share a Redis instance with other applications # and want to avoid key collisions. The default prefix is # "@upstash/ratelimit" prefix="@upstash/ratelimit", ) # Use a constant string to limit all requests with a single ratelimit # Or use a user ID, API key or IP address for individual limits. identifier = "api" response = ratelimit.limit(identifier) if not response.allowed: print("Unable to process at this time") else: do_expensive_calculation() print("Here you go!") ---------------------------------------- TITLE: Creating Next.js API Endpoint with Upstash Redis DESCRIPTION: TypeScript code for a Next.js API route that uses Upstash Redis to implement a simple counter that increments on each request. LANGUAGE: ts CODE: import { Redis } from "@upstash/redis"; import type { NextApiRequest, NextApiResponse } from "next"; import { Config } from "sst/node/config"; const redis = new Redis({ url: Config.UPSTASH_REDIS_REST_URL, token: Config.UPSTASH_REDIS_REST_TOKEN, }); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const count = await redis.incr("counter"); res.status(200).json({ count }); } ---------------------------------------- TITLE: Fixed Window Rate Limiting Commands Table DESCRIPTION: Shows Redis command costs for Fixed Window algorithm based on cache result and algorithm state LANGUAGE: markdown CODE: | Cache Result | Algorithm State | Command Count | Commands | | ------------ | --------------- | ------------- | ------------------- | | Hit/Miss | First | 3 | EVAL, INCR, PEXPIRE | | Hit/Miss | Intermediate | 2 | EVAL, INCR | | Miss | Rate-Limited | 2 | EVAL, INCR | | Hit | Rate-Limited | 0 | _utilized cache_ | ---------------------------------------- TITLE: Implementing Feature Creation API in Next.js DESCRIPTION: This serverless API function adds a new element to the sorted set 'roadmap' in Redis. It uses the 'NX' flag with ZADD to prevent overwriting existing feature requests with the same title. LANGUAGE: javascript CODE: import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; if (!title) { redis.quit(); res.json({ error: "Feature can not be empty", }); } else if (title.length < 70) { await redis.zadd("roadmap", "NX", 1, title); redis.quit(); res.json({ body: "success", }); } else { redis.quit(); res.json({ error: "Max 70 characters please.", }); } }; ---------------------------------------- TITLE: Implementing Redis Transaction in TypeScript DESCRIPTION: Creates a Redis transaction using multi() to execute commands atomically. This example sets a value for key 'foo' and then retrieves it, with both operations guaranteed to execute without other clients' commands interrupting. LANGUAGE: typescript CODE: const tx = redis.multi(); tx.set("foo", "bar"); tx.get("foo"); const res = await tx.exec(); ---------------------------------------- TITLE: Implementing Sliding Window Rate Limiting with Redis - Multi Regional DESCRIPTION: Creates a rate limiter using sliding window algorithm with multi-regional Redis setup, with a warning about high command volume. LANGUAGE: typescript CODE: const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), }); ---------------------------------------- TITLE: Working with Redis Transactions in Python DESCRIPTION: Shows how to use Redis transactions through the multi() method to ensure atomic execution of a batch of commands, where no other commands are executed during the transaction. LANGUAGE: python CODE: pipeline = redis.multi() pipeline.set("foo", 1) pipeline.incr("foo") pipeline.get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ---------------------------------------- TITLE: Adding and Updating Elements in Redis Sorted Set using ZADD in Python DESCRIPTION: This snippet demonstrates various uses of the ZADD command in Redis using Python. It shows how to add new elements, update existing ones, and use different options like nx, xx, gt, and lt. LANGUAGE: python CODE: # Add three elements assert redis.zadd("myset", { "one": 1, "two": 2, "three": 3 }) == 3 # No element is added since "one" and "two" already exist assert redis.zadd("myset", { "one": 1, "two": 2 }, nx=True) == 0 # New element is not added since it does not exist assert redis.zadd("myset", { "new-element": 1 }, xx=True) == 0 # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 ---------------------------------------- TITLE: Implementing Lambda Counter Function DESCRIPTION: TypeScript implementation of the Lambda function that increments and returns a counter value using Upstash Redis. LANGUAGE: typescript CODE: import { Redis } from '@upstash/redis'; const redis = Redis.fromEnv(); export const handler = async function() { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ---------------------------------------- TITLE: Initializing Cloudflare Worker Project with Wrangler CLI DESCRIPTION: This snippet shows the process of creating a new Cloudflare Worker project using the Wrangler CLI. It sets up a TypeScript-based Hello World example. LANGUAGE: shell CODE: ➜ tutorials > ✗ npx wrangler init ╭ Create an application with Cloudflare Step 1 of 3 │ ├ In which directory do you want to create your application? │ dir ./greetings-cloudflare │ ├ What would you like to start with? │ category Hello World example │ ├ Which template would you like to use? │ type Hello World Worker │ ├ Which language do you want to use? │ lang TypeScript │ ├ Copying template files │ files copied to project directory │ ├ Updating name in `package.json` │ updated `package.json` │ ├ Installing dependencies │ installed via `npm install` │ ╰ Application created ╭ Configuring your application for Cloudflare Step 2 of 3 │ ├ Installing @cloudflare/workers-types │ installed via npm │ ├ Adding latest types to `tsconfig.json` │ added @cloudflare/workers-types/2023-07-01 │ ├ Retrieving current workerd compatibility date │ compatibility date 2024-10-22 │ ├ Do you want to use git for version control? │ no git │ ╰ Application configured ---------------------------------------- TITLE: Using PERSIST Command to Remove Expiration Timeout in Redis with Python DESCRIPTION: This example demonstrates how to use the PERSIST command to remove a timeout from a Redis key. It first sets a key with a value, applies an expiration timeout using EXPIRE, verifies the TTL is set, then removes the timeout with PERSIST and confirms the TTL is now -1 (indicating no expiration). LANGUAGE: python CODE: redis.set("key1", "Hello") redis.expire("key1", 10) assert redis.ttl("key1") == 10 redis.persist("key1") assert redis.ttl("key1") == -1 ---------------------------------------- TITLE: Configuring Celery with Upstash Redis DESCRIPTION: Python code to set up Celery with Upstash Redis as both broker and backend. It loads environment variables, constructs a secure Redis connection string with TLS, and defines a sample task. LANGUAGE: python CODE: import os from celery import Celery from dotenv import load_dotenv load_dotenv() # Configure Celery with Upstash Redis UPSTASH_REDIS_HOST = os.getenv("UPSTASH_REDIS_HOST") UPSTASH_REDIS_PORT = os.getenv("UPSTASH_REDIS_PORT") UPSTASH_REDIS_PASSWORD = os.getenv("UPSTASH_REDIS_PASSWORD") connection_link = f"rediss://:{UPSTASH_REDIS_PASSWORD}@{UPSTASH_REDIS_HOST}:{UPSTASH_REDIS_PORT}?ssl_cert_reqs=required" celery_app = Celery("tasks", broker=connection_link, backend=connection_link) @celery_app.task def add(x, y): return x + y ---------------------------------------- TITLE: Retrieving Stream Entries with XRANGE in TypeScript DESCRIPTION: This example demonstrates how to use Redis XRANGE command to retrieve all entries from a stream using the full range specifiers ('-' for the lowest ID and '+' for the highest ID). The returned object contains stream entries keyed by their stream ID, with each entry containing field-value pairs. LANGUAGE: ts CODE: const entries = redis.xrange(key, "-", "+"); console.log(entries) // { // "1548149259438-0": { // "field1": "value1", // "field2": "value2" // }, // "1548149259438-1": { // "field1": "value3", // "field2": "value4" // } // } ---------------------------------------- TITLE: Using Auto-Pipelining with Batch Operations in Redis DESCRIPTION: Demonstrates how auto-pipelining works with asynchronous operations and batch requests. This example shows how multiple Redis commands are automatically batched into a single pipeline request, reducing network overhead and improving performance. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv({ latencyLogging: false, enableAutoPipelining: true }); // async call to redis. Not executed right away, instead // added to the pipeline redis.hincrby("Brooklyn", "visited", 1); // making requests in batches const brooklynInfo = Promise.all([ redis.hget("Brooklyn", "coordinates"), redis.hget("Brooklyn", "population") ]); // when we call await, the three commands are executed // as a pipeline automatically. A single PIPELINE command // is executed instead of three requests and the results // are returned: const [ coordinates, population ] = await brooklynInfo; ---------------------------------------- TITLE: Trimming Redis List with LTRIM Command in TypeScript DESCRIPTION: Demonstrates how to use LTRIM command to trim a Redis list. First pushes multiple elements to a list using LPUSH, then trims the list to keep only elements at indices 1 and 2. The resulting list contains only the elements 'b' and 'c'. LANGUAGE: typescript CODE: await redis.lpush("key", "a", "b", "c", "d"); await redis.ltrim("key", 1, 2); // the list is now ["b", "c"] ---------------------------------------- TITLE: Retrieving All Fields from a Redis Hash using HGETALL DESCRIPTION: This example demonstrates how to set multiple fields in a Redis hash using HSET and then retrieve all fields at once using HGETALL. The returned value is an object containing all field-value pairs from the hash. LANGUAGE: typescript CODE: await redis.hset("key", { field1: "value1", field2: "value2", }); const hash = await redis.hgetall("key"); console.log(hash); // { field1: "value1", field2: "value2" } ---------------------------------------- TITLE: External Weather API Integration with Caching in Elixir DESCRIPTION: Method to fetch weather data from WeatherAPI and cache the response in Redis. Includes error handling and response processing. LANGUAGE: elixir CODE: defp fetch_weather_from_api(location) do weather_api_key = System.get_env("WEATHER_API_KEY") url = "http://api.weatherapi.com/v1/current.json?key=#{weather_api_key}&q=#{location}&aqi=no" case HTTPoison.get(url) do {:ok, %{status_code: 200, body: body}} -> weather_info = body |> Jason.decode!() |> get_weather_info() # Cache the weather response in Redis for 8 hours cache_weather_response(location, Jason.encode!(weather_info)) {:ok, weather_info} {:ok, %{status_code: status_code, body: body}} -> {:error, "#{body} (#{status_code})"} {:error, _reason} -> {:error, "Failed to fetch weather data."} end end ---------------------------------------- TITLE: Implementing Redis Counter in Google Cloud Function DESCRIPTION: A Node.js function that uses ioredis client to increment a counter in Redis and return the current count. The function establishes a persistent Redis connection and handles HTTP GET requests. LANGUAGE: javascript CODE: var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.helloGET = async (req, res) => { let count = await client.incr("counter"); res.send("Page view:" + count); }; ---------------------------------------- TITLE: Using ZLEXCOUNT to Count Elements in Redis Sorted Set (Python) DESCRIPTION: This example demonstrates how to use the ZLEXCOUNT command in Redis to count elements in a sorted set. It first adds elements to a set named 'myset' using zadd, then uses zlexcount to count all elements between the lexicographical bounds '-' and '+'. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zlexcount("myset", "-", "+") == 3 ---------------------------------------- TITLE: Connecting with Redigo in Go DESCRIPTION: Example of connecting to Upstash Redis using the Redigo client library in Go, showing connection setup with TLS and basic Redis operations. LANGUAGE: go CODE: func main() { c, err := redis.Dial("tcp", "YOUR_ENDPOINT:YOUR_PORT", redis.DialUseTLS(true)) if err != nil { panic(err) } _, err = c.Do("AUTH", "YOUR_PASSWORD") if err != nil { panic(err) } _, err = c.Do("SET", "foo", "bar") if err != nil { panic(err) } value, err := redis.String(c.Do("GET", "foo")) if err != nil { panic(err) } println(value) } ---------------------------------------- TITLE: Using ZRANGE with BYSCORE Sorting in Redis with Python DESCRIPTION: Demonstrates using the zrange command with the sortby parameter set to BYSCORE to sort elements by their score values rather than by index. Adds elements to a sorted set and retrieves them based on score ordering. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, sortby="BYSCORE") == ["a", "b"] ---------------------------------------- TITLE: Loading a Lua Script into Redis Script Cache with TypeScript DESCRIPTION: This example shows how to load a Lua script into the Redis script cache using TypeScript. The script retrieves a value using the GET command for a given key and returns that value. The scriptLoad method returns the SHA1 hash of the loaded script that can be used for future script executions. LANGUAGE: typescript CODE: const script = ` local value = redis.call('GET', KEYS[1]) return value `; const sha1 = await redis.scriptLoad(script); ---------------------------------------- TITLE: Redis Weather Data Caching with Expiration in Elixir DESCRIPTION: Method to store weather data in Redis with an 8-hour expiration time using Redix SET command with EX parameter. LANGUAGE: elixir CODE: defp cache_weather_response(location, weather_data) do case Redix.command(:redix, ["SET", "weather:#{location}", weather_data, "EX", 8 * 60 * 60]) do {:ok, _} -> :ok {:error, _reason} -> {:error, "Failed to cache weather data."} end end ---------------------------------------- TITLE: Implementing Redis Counter in Supabase Edge Function DESCRIPTION: TypeScript implementation of a Redis counter that tracks function invocations per region using Upstash Redis. The code increments a counter for each region and returns total counts across all regions. LANGUAGE: typescript CODE: import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; import { Redis } from "https://deno.land/x/upstash_redis@v1.19.3/mod.ts"; console.log(`Function "upstash-redis-counter" up and running!`); serve(async (_req) => { try { const redis = new Redis({ url: Deno.env.get("UPSTASH_REDIS_REST_URL")!, token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!, }); const deno_region = Deno.env.get("DENO_REGION"); if (deno_region) { // Increment region counter await redis.hincrby("supa-edge-counter", deno_region, 1); } else { // Increment localhost counter await redis.hincrby("supa-edge-counter", "localhost", 1); } // Get all values const counterHash: Record | null = await redis.hgetall( "supa-edge-counter" ); const counters = Object.entries(counterHash!) .sort(([, a], [, b]) => b - a) // sort desc .reduce( (r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v }, }), { total: 0, regions: {}, } ); return new Response(JSON.stringify({ counters }), { status: 200 }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 200, }); } }); ---------------------------------------- TITLE: Deploying the AWS SAM Application with Guided Setup DESCRIPTION: Command to deploy the serverless application using guided setup which will prompt for Upstash Redis environment variables. LANGUAGE: shell CODE: sam deploy --guided ---------------------------------------- TITLE: Clearing Nested JSON Values using Path Selector DESCRIPTION: Example of clearing JSON values at a specific path within the JSON structure. Uses JSONPath syntax to target nested values. LANGUAGE: typescript CODE: await redis.json.clear("key", "$.my.key"); ---------------------------------------- TITLE: Setting Expiration on Redis Keys in Python DESCRIPTION: This code snippet demonstrates how to use the Redis EXPIRE command in Python. It shows setting an expiration time using both seconds and a timedelta object, and verifies the key's existence after expiration. LANGUAGE: python CODE: # With seconds redis.set("mykey", "Hello") redis.expire("mykey", 5) assert redis.get("mykey") == "Hello" time.sleep(5) assert redis.get("mykey") is None # With a timedelta redis.set("mykey", "Hello") redis.expire("mykey", datetime.timedelta(seconds=5)) ---------------------------------------- TITLE: Configuring BullMQ Queue with Upstash Redis Connection DESCRIPTION: JavaScript implementation showing how to initialize a BullMQ queue with Upstash Redis connection settings and add jobs to the queue. Demonstrates connection configuration and basic job creation. LANGUAGE: javascript CODE: import { Queue } from 'bullmq'; const myQueue = new Queue('foo', { connection: { host: "UPSTASH_REDIS_ENDPOINT", port: 6379, password: "UPSTASH_REDIS_PASSWORD", tls: {} }}); async function addJobs() { await myQueue.add('myJobName', { foo: 'bar' }); await myQueue.add('myJobName', { qux: 'baz' }); } await addJobs(); ---------------------------------------- TITLE: Inefficient vs Efficient Auto-Pipelining Usage DESCRIPTION: Contrasts inefficient and efficient ways to use auto-pipelining. The first example shows how awaiting each command individually defeats the purpose of pipelining, while the second example demonstrates the correct approach using Promise.all to batch multiple commands. LANGUAGE: typescript CODE: const foo = await redis.get("foo") // makes a PIPELINE call const bar = await redis.get("bar") // makes another PIPELINE call LANGUAGE: typescript CODE: // makes a single PIPELINE call: const [ foo, bar ] = await Promise.all([ redis.get("foo"), redis.get("bar") ]) ---------------------------------------- TITLE: Removing Single Element from Redis List using RPOP in Python DESCRIPTION: This snippet demonstrates how to use the RPOP command to remove and return the last element from a Redis list. It first pushes elements to the list using RPUSH, then uses RPOP to remove the last element. LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.rpop("mylist") == "three" ---------------------------------------- TITLE: Deleting JSON Key in Redis using Python DESCRIPTION: This code snippet demonstrates how to use the JSON.DEL command in Redis to delete a specific path within a JSON document. It takes the key of the JSON entry and the path to delete as arguments. LANGUAGE: python CODE: redis.json.del("key", "$.path.to.value") ---------------------------------------- TITLE: Deleting JSON Key in Redis using Python DESCRIPTION: This code snippet demonstrates how to use the JSON.DEL command in Redis to delete a specific path within a JSON document. It takes the key of the JSON entry and the path to delete as arguments. LANGUAGE: python CODE: redis.json.del("key", "$.path.to.value") ---------------------------------------- TITLE: Performing Set Intersection with Aggregation using ZINTER in Redis DESCRIPTION: This example shows how to use ZINTER with aggregation. It intersects two sets, includes scores in the result, and uses the SUM aggregation function to combine scores from both sets. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zinter(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ---------------------------------------- TITLE: Dockerfile for Node.js Applications with Upstash Redis DESCRIPTION: Multi-stage Dockerfile for building and running a Node.js application that connects to Upstash Redis. It uses Alpine Linux for a small footprint, sets up proper dependencies, and configures a non-root user for security. LANGUAGE: dockerfile CODE: FROM node:18-alpine AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nodejs COPY --from=deps /app/node_modules ./node_modules COPY . . USER node EXPOSE 3000 ENV PORT 3000 CMD ["npm", "run", "start"] ---------------------------------------- TITLE: Creating Project Directory and Installing Dependencies DESCRIPTION: Commands to set up the project directory and install the required npm packages for the application. LANGUAGE: bash CODE: mkdir app_runner_example cd app_runner_example LANGUAGE: bash CODE: npm init npm install ioredis ---------------------------------------- TITLE: Checking Set Membership with Redis SMISMEMBER in Python DESCRIPTION: Example demonstrating how to use SMISMEMBER command to check if multiple values exist in a Redis set. First creates a set with three members, then performs two membership checks - one with existing and non-existing members, and another with only non-existing members. LANGUAGE: python CODE: redis.sadd("myset", "one", "two", "three") assert redis.smismember("myset", "one", "four") == [True, False] assert redis.smismember("myset", "four", "five") == [False, False] ---------------------------------------- TITLE: Adding Basic Stream Entry with Redis XADD in TypeScript DESCRIPTION: Demonstrates how to append a basic entry to a Redis stream using XADD command. Uses auto-generated ID and adds name and age fields to the stream. LANGUAGE: typescript CODE: await redis.xadd(key, "*", { name: "John Doe", age: 30 }); ---------------------------------------- TITLE: Authentication with Bearer Token in Upstash Redis REST API DESCRIPTION: Example of authenticating to Upstash Redis REST API using a Bearer token in the Authorization header. This is the recommended authentication method for securing API requests. LANGUAGE: shell CODE: curl -X POST https://us1-merry-cat-32748.upstash.io/info \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ---------------------------------------- TITLE: Conditional Key Setting in Redis with NX and XX Options DESCRIPTION: This example shows how to use the nx and xx flags to conditionally set keys. The nx flag only sets the key if it doesn't exist, while xx only sets the key if it already exists. LANGUAGE: python CODE: # Only set the key if it does not already exist. assert redis.set("key", "value", nx=True) == False # Only set the key if it already exists. assert redis.set("key", "value", xx=True) == True ---------------------------------------- TITLE: Performing Set Union Operation in Redis using TypeScript DESCRIPTION: Demonstrates how to use the SUNION command to get the union of two Redis sets. The example shows adding elements to two different sets and then performing a union operation to get all unique elements from both sets. LANGUAGE: typescript CODE: await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const union = await redis.sunion("set1", "set2"); console.log(union); // ["a", "b", "c", "d", "e"] ---------------------------------------- TITLE: Implementing Sliding Window Ratelimiting with Upstash Redis in Python DESCRIPTION: Creates a Sliding Window ratelimiter that allows 10 requests within a rolling 10-second window. This algorithm improves on Fixed Window by using a weighted calculation between adjacent time windows to avoid boundary problems. LANGUAGE: python CODE: from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=SlidingWindow(max_requests=10, window=10), ) ---------------------------------------- TITLE: ZINTERSTORE with Weighted Scores in Redis DESCRIPTION: Shows how to use ZINTERSTORE with weighted scores, where each input set's scores are multiplied by the specified weights before computing the intersection. LANGUAGE: typescript CODE: await redis.zadd("key1", { score: 1, member: "member1" }) await redis.zadd("key2",{ score: 1, member: "member1" },{ score: 2, member: "member2" }) const res = await redis.zinterstore("destination",2,["key1", "key2"],{ weights: [2, 3] }); console.log(res) // 1 ---------------------------------------- TITLE: Deploying CDK Stack to AWS DESCRIPTION: Commands to synthesize the CloudFormation template, bootstrap the AWS environment, and deploy the CDK stack. LANGUAGE: shell CODE: cdk synth cdk bootstrap cdk deploy ---------------------------------------- TITLE: JSON.SET with NX Flag in Redis using Python DESCRIPTION: Sets a JSON value at the specified path only if it does not already exist. The nx=true parameter ensures the operation is conditional on the path not existing. LANGUAGE: python CODE: value = ... redis.json.set(key, "$.path", value, nx=true) ---------------------------------------- TITLE: Implementing Coin Price List Component in Next.js index.js DESCRIPTION: This code defines the main component for the coin price list application. It uses Apollo Client's useQuery hook to fetch coin data from the Redis database via GraphQL, then renders the data in a table format. LANGUAGE: javascript CODE: import Head from "next/head"; import styles from "../styles/Home.module.css"; import { gql, useQuery } from "@apollo/client"; import React from "react"; const GET_COIN_LIST = gql` query { redisLRange(key: "coins", start: 0, stop: 6) } `; export default function Home() { let coins = []; const { loading, error, data } = useQuery(GET_COIN_LIST); if (!loading && !error) { for (let x of data.redisLRange) { let dd = JSON.parse(x); coins.push(dd); } } return (
Create Next App

Coin Price List

{!loading ? ( coins.map((item, ind) => ( )) ) : ( )}
{item.name} ${item.price}
); } ---------------------------------------- TITLE: Querying Member Score in Redis Sorted Set using Python DESCRIPTION: This example demonstrates how to use the ZSCORE command in Redis with Python. It first adds members to a sorted set 'myset' using zadd, then retrieves and asserts the score of a specific member. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zscore("myset", "a") == 1 ---------------------------------------- TITLE: Querying Redis Stream Entries with XRANGE in Python DESCRIPTION: Example demonstrating how to use the XRANGE command to retrieve all entries from a Redis stream. The example shows fetching entries from the earliest (-) to latest (+) IDs, returning a dictionary of stream entries mapped by their IDs with associated field-value pairs. LANGUAGE: python CODE: entries = redis.xrange(key, "-", "+") print(entries) # { # "1548149259438-0": { # "field1": "value1", # "field2": "value2" # }, # "1548149259438-1": { # "field1": "value3", # "field2": "value4" # } # } ---------------------------------------- TITLE: Appending String Values in Redis using Python DESCRIPTION: Demonstrates how to append a string value to an existing key in Redis. The example shows setting an initial value, appending additional text, and verifying the final result. The APPEND command returns the total length of the resulting string after the append operation. LANGUAGE: python CODE: redis.set("key", "Hello") assert redis.append("key", " World") == 11 assert redis.get("key") == "Hello World" ---------------------------------------- TITLE: Retrieving Multiple Keys with MGET in TypeScript DESCRIPTION: This snippet demonstrates how to use the MGET command to retrieve multiple keys from Redis in a single operation. It defines a custom type and uses type inference for the returned values. LANGUAGE: typescript CODE: type MyType = { a: number; b: string; } const values = await redis.mget("key1", "key2", "key3"); // values.length -> 3 ---------------------------------------- TITLE: Setting Keys with Expiration in Redis DESCRIPTION: This example demonstrates how to set keys with expiration times using both seconds (ex) and milliseconds (px) parameters. The keys will automatically be deleted after the specified time. LANGUAGE: python CODE: # Set the key to expire in 10 seconds. assert redis.set("key", "value", ex=10) == True # Set the key to expire in 10000 milliseconds. assert redis.set("key", "value", px=10000) == True ---------------------------------------- TITLE: Configuring CDK Stack for Counter Function DESCRIPTION: Sets up the AWS CDK stack to deploy the counter function as a Lambda, including environment variables for Redis connection and function URL configuration. LANGUAGE: typescript CODE: import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new lambda.Function(this, 'CounterFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'api'), { bundling: { image: lambda.Runtime.PYTHON_3_9.bundlingImage, command: [ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output' ], }, }), runtime: lambda.Runtime.PYTHON_3_9, handler: 'index.handler', environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ---------------------------------------- TITLE: Navigating to the SAM Application Directory DESCRIPTION: Command to navigate to the newly created SAM application directory. LANGUAGE: shell CODE: cd sam-app ---------------------------------------- TITLE: Setting Multiple Hash Fields with HSET in TypeScript DESCRIPTION: This example demonstrates how to use the HSET command to set multiple fields in a Redis hash. It sets three fields (id, username, and name) for a key named 'key'. LANGUAGE: typescript CODE: await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); ---------------------------------------- TITLE: Initializing Redis Client with Auto-Pipelining Using fromEnv DESCRIPTION: Creates a Redis client with auto-pipelining enabled using the fromEnv method, which loads connection details from environment variables. This configuration disables latency logging and enables auto-pipelining for performance optimization. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv({ latencyLogging: false, enableAutoPipelining: true }); ---------------------------------------- TITLE: Implementing Consumer Application with Bull and Upstash Redis DESCRIPTION: This JavaScript code implements the consumer application using Bull and Upstash Redis. It creates a task queue and processes jobs from it continuously. LANGUAGE: javascript CODE: var Queue = require("bull"); var settings = { stalledInterval: 300000, // How often check for stalled jobs (use 0 for never checking). guardInterval: 5000, // Poll interval for delayed jobs and added jobs. drainDelay: 300, // A timeout for when the queue is in drained state (empty waiting for jobs). }; var taskQueue = new Queue( "employee registration", { redis: { port: 32016, host: "us1-upward-ant-32016.upstash.io", password: "ake4ff120d6b4216df220736be7eab087", tls: {}, }, }, settings ); taskQueue .process(function (job, done) { console.log(job.data); // TODO process the new employee event done(); }) .catch((err) => { console.log(err); }); ---------------------------------------- TITLE: BITFIELD Get Operations in Redis Python DESCRIPTION: Shows how to retrieve multiple 8-bit unsigned integers from different offsets in a Redis string using BITFIELD command. LANGUAGE: python CODE: redis.set("mykey", "\x05\x06\x07") result = redis.bitfield("mykey") \ .get("u8", 0) \ .get("u8", 8) \ .get("u8", 16) \ .execute() assert result == [5, 6, 7] ---------------------------------------- TITLE: Checking Script Existence in Redis with TypeScript DESCRIPTION: Example showing how to check if multiple scripts exist in Redis script cache using their SHA1 hashes. The command returns an array of numbers where 1 indicates the script exists and 0 indicates it doesn't. LANGUAGE: typescript CODE: await redis.scriptExists("", "") // Returns 1 // [1, 0] ---------------------------------------- TITLE: Performing Set Intersection with SINTER in Redis using TypeScript DESCRIPTION: This example demonstrates how to use the SINTER command to find the intersection between two Redis sets. It first adds elements to two sets using SADD, then performs the intersection operation using SINTER. LANGUAGE: typescript CODE: await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const intersection = await redis.sinter("set1", "set2"); console.log(intersection); // ["c"] ---------------------------------------- TITLE: Using STRLEN Command in Redis with TypeScript DESCRIPTION: This example demonstrates how to use the STRLEN command in Redis using TypeScript. It first sets a string value for a key and then retrieves its length using the strlen method. LANGUAGE: typescript CODE: await redis.set("key", "helloworld") const length = await redis.strlen("key"); console.log(length); // 10 ---------------------------------------- TITLE: Configuring Serverless Framework with YAML DESCRIPTION: Serverless Framework configuration file that defines the service, runtime environment, environment variables, and HTTP endpoint for the Lambda function. LANGUAGE: yaml CODE: service: ratelimit-serverless provider: name: aws runtime: nodejs20.x environment: UPSTASH_REDIS_REST_URL: ${env:UPSTASH_REDIS_REST_URL} UPSTASH_REDIS_REST_TOKEN: ${env:UPSTASH_REDIS_REST_TOKEN} functions: ratelimit: handler: handler.ratelimit events: - httpApi: path: / method: get ---------------------------------------- TITLE: Starting Development Environment for Serverless DESCRIPTION: Command to start a local development environment for the Serverless application. LANGUAGE: shell CODE: serverless dev ---------------------------------------- TITLE: Connecting with upstash-redis HTTP Client in TypeScript DESCRIPTION: Example of connecting to Upstash Redis using the HTTP-based upstash-redis client library, recommended for serverless functions due to better handling of concurrent connections. LANGUAGE: typescript CODE: import { Redis } from '@upstash/redis'; const redis = new Redis({ url: 'UPSTASH_REDIS_REST_URL', token: 'UPSTASH_REDIS_REST_TOKEN' }); (async () => { try { const data = await redis.get('key'); console.log(data); } catch (error) { console.error(error); } })(); ---------------------------------------- TITLE: Pushing Elements to Redis List Head using LPUSH in TypeScript DESCRIPTION: This example demonstrates how to use the LPUSH command to add elements to the head of a Redis list. It shows pushing multiple elements at once and a single element in separate operations, displaying the updated list length after each push. LANGUAGE: typescript CODE: const length1 = await redis.lpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.lpush("key", "d"); console.log(length2); // 4 ---------------------------------------- TITLE: React Notification Component Implementation DESCRIPTION: Main React component implementation that fetches notifications from Redis and displays them using react-toastify. Includes version tracking using localStorage to prevent duplicate notifications. LANGUAGE: javascript CODE: import logo from "./logo.svg"; import "./App.css"; import { toast, ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { useEffect } from "react"; function App() { useEffect(() => { async function fetchData() { try { let version = localStorage.getItem("notification-version"); version = version ? version : 0; const response = await fetch( "REPLACE_UPSTASH_REDIS_REST_URL/zrevrangebyscore/messages/+inf/" + version + "/WITHSCORES/LIMIT/0/1", { headers: { Authorization: "Bearer REPLACE_UPSTASH_REDIS_REST_TOKEN", }, } ); const res = await response.json(); const v = parseInt(res.result[1]); if (v) { localStorage.setItem("notification-version", v + 1); } toast(res.result[0]); } catch (e) { console.error(e); } } fetchData(); }); return (
logo

Edit src/App.js and save to reload.

Learn React
); } export default App; ---------------------------------------- TITLE: Moving Elements Between Redis Lists Using LMOVE Command - Python DESCRIPTION: Demonstrates moving elements between two Redis lists using the LMOVE command. The example shows pushing elements to source and destination lists, then moving an element from the right of the source list to the left of the destination list, followed by verification of the operation. LANGUAGE: python CODE: redis.rpush("source", "one", "two", "three") redis.lpush("destination", "four", "five", "six") assert redis.lmove("source", "destination", "RIGHT", "LEFT") == "three" assert redis.lrange("source", 0, -1) == ["one", "two"] ---------------------------------------- TITLE: Checking Set Membership with SISMEMBER in Python Redis DESCRIPTION: Example demonstrates how to check if a member exists in a Redis set. First adds multiple members to a set using SADD, then verifies membership using SISMEMBER which returns a boolean value. LANGUAGE: python CODE: redis.sadd("set", "a", "b", "c") assert redis.sismember("set", "a") == True ---------------------------------------- TITLE: Checking Key Existence with EXISTS Command in Redis using Python DESCRIPTION: This example demonstrates how to use the EXISTS command in Redis to check if one or more keys exist. It sets two keys, checks their existence, deletes one, and checks again. LANGUAGE: python CODE: redis.set("key1", "Hello") redis.set("key2", "World") assert redis.exists("key1", "key2") == 2 redis.delete("key1") assert redis.exists("key1", "key2") == 1 ---------------------------------------- TITLE: Configuring Redis Client for Local and Production Environments DESCRIPTION: This JavaScript snippet demonstrates how to set up a Redis client that can work with both local development (using a tunnel) and production environments. It uses environment variables to determine the correct Redis URL to use. LANGUAGE: javascript CODE: const redis = require("redis"); // Local Redis URL for development const LOCAL_REDIS_URL = 'redis://localhost:10000'; // Replace with your actual local address const REDIS_URL = process.env.NODE_ENV === 'development' ? LOCAL_REDIS_URL : process.env.REDIS_URL; const client = redis.createClient({ url: REDIS_URL }); client.on("error", function(error) { console.error(error); }); // Rest of your Redis-related code ---------------------------------------- TITLE: Configuring AWS CDK Stack for Lambda Function DESCRIPTION: Sets up the CDK stack to create the Lambda function, configure its environment, and expose it via a function URL. LANGUAGE: typescript CODE: import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new lambda.Function(this, 'CounterFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'api'), { bundling: { image: lambda.Runtime.PYTHON_3_9.bundlingImage, command: [ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output' ], }, }), runtime: lambda.Runtime.PYTHON_3_9, handler: 'index.handler', environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ---------------------------------------- TITLE: Installing Sidekiq Dependencies with Ruby Bundler DESCRIPTION: This snippet shows how to initialize a Ruby project and add Sidekiq as a dependency using Bundler. LANGUAGE: bash CODE: bundle init bundle add sidekiq ---------------------------------------- TITLE: Setting Multiple Redis Keys Conditionally with MSETNX DESCRIPTION: Demonstrates how to use the MSETNX command to set multiple key-value pairs atomically, only if none of the keys already exist. The command returns true if all keys were set successfully, false if any key already existed. LANGUAGE: typescript CODE: redis.msetnx({ "key1": "value1", "key2": "value2" }) ---------------------------------------- TITLE: Transaction Response Format in Upstash Redis REST API DESCRIPTION: JSON response format for a successful transaction in Upstash Redis REST API. Each item in the response array corresponds to a command in the same order within the transaction, containing either a result or an error. LANGUAGE: json CODE: [{"result":"RESPONSE_A"},{"result":"RESPONSE_B"},{"error":"ERR ..."}, ...] ---------------------------------------- TITLE: Pushing Elements to List Head with LPUSH in Python DESCRIPTION: This example demonstrates using the LPUSH command to add multiple elements to the beginning of a Redis list. It then verifies the list length and contents using LRANGE. LANGUAGE: python CODE: assert redis.lpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] ---------------------------------------- TITLE: Counting Set Bits with Redis BITCOUNT in Python DESCRIPTION: This example demonstrates how to use the BITCOUNT command in Redis to count set bits. It sets bits at positions 7, 8, and 9, then counts the set bits both with and without specifying a range. LANGUAGE: python CODE: redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) redis.setbit("mykey", 9, 1) # With range assert redis.bitcount("mykey", 0, 10) == 3 # Without range assert redis.bitcount("mykey") == 3 ---------------------------------------- TITLE: Basic Key Deletion in Redis using TypeScript DESCRIPTION: Shows how to delete multiple keys directly using the del command with individual key arguments. LANGUAGE: typescript CODE: await redis.del("key1", "key2"); ---------------------------------------- TITLE: Deleting Hash Fields with Redis HDEL Command in Python DESCRIPTION: Example demonstrating how to use HDEL command to remove multiple fields from a Redis hash. The example first sets two hash fields using HSET and then deletes both fields using HDEL, confirming that 2 fields were removed. LANGUAGE: python CODE: redis.hset("myhash", "field1", "Hello") redis.hset("myhash", "field2", "World") assert redis.hdel("myhash", "field1", "field2") == 2 ---------------------------------------- TITLE: Configuring Upstash Ratelimit Strapi Plugin in TypeScript DESCRIPTION: TypeScript configuration for the Upstash Ratelimit Strapi plugin. This setup includes enabling the plugin, setting Redis credentials, and defining rate limiting strategies for different API routes. LANGUAGE: typescript CODE: export default () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s", }, }, ], prefix: "@strapi", }, }, }); ---------------------------------------- TITLE: Getting Hash Field String Length in Redis with Python DESCRIPTION: Demonstrates how to get the string length of a field value in a Redis hash using the HSTRLEN command. Returns 0 if the hash or field doesn't exist, otherwise returns the length of the string value. LANGUAGE: python CODE: length = redis.hstrlen("key", "field") ---------------------------------------- TITLE: Using GETDEL with TypeScript in Upstash Redis DESCRIPTION: Example showing how to use the GETDEL command with type safety in TypeScript. The command retrieves a value and deletes the key in a single operation, returning the typed value stored at the key. LANGUAGE: typescript CODE: type MyType = { a: number; b: string; } await redis.getdel("key"); // returns {a: 1, b: "2"} ---------------------------------------- TITLE: Checking Hash Field Existence in Redis using TypeScript DESCRIPTION: Demonstrates how to check if a field exists in a Redis hash using the hexists command. The example first sets a hash field value using hset, then checks for its existence using hexists. Returns 1 if the field exists, 0 if it doesn't. LANGUAGE: typescript CODE: await redis.hset("key", "field", "value"); const exists = await redis.hexists("key", "field"); console.log(exists); // 1 ---------------------------------------- TITLE: Checking Key Existence with Redis EXISTS Command in TypeScript DESCRIPTION: This snippet demonstrates how to use the Redis EXISTS command to check for the existence of multiple keys. It sets two keys, then checks for three keys, including one that wasn't set. The command returns the number of existing keys. LANGUAGE: typescript CODE: await redis.set("key1", "value1") await redis.set("key2", "value2") const keys = await redis.exists("key1", "key2", "key3"); console.log(keys) // 2 ---------------------------------------- TITLE: Using LINSERT Command in Python to Insert an Element Before Another in a Redis List DESCRIPTION: This example demonstrates how to use the LINSERT command in Python to insert an element into a Redis list. It first creates a list with rpush containing elements 'a', 'b', and 'c', then inserts the element 'x' before 'b'. LANGUAGE: python CODE: redis.rpush("key", "a", "b", "c") redis.linsert("key", "before", "b", "x") ---------------------------------------- TITLE: Setting a Bit in Redis String with SETBIT in TypeScript DESCRIPTION: Sets a bit at a specified offset in a Redis string and returns the original bit value. This example sets the bit at offset 4 to value 1 for the given key. LANGUAGE: typescript CODE: const originalBit = await redis.setbit(key, 4, 1); ---------------------------------------- TITLE: Basic Redis EVAL Script Example DESCRIPTION: Demonstrates executing a Lua script that retrieves a value using Redis GET command. The script first sets a key-value pair and then executes a Lua script to retrieve it. LANGUAGE: python CODE: script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval(script, keys=["mykey"]) == "Hello" ---------------------------------------- TITLE: Redis ZUNIONSTORE with Weights in Python DESCRIPTION: Advanced example demonstrating zunionstore with weighted sets. Applies different weights to each set before computing the union. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ---------------------------------------- TITLE: Configuring Serverless YAML for Java Lambda Function DESCRIPTION: YAML configuration for the serverless.yml file specifying AWS as the provider, Java 17 as the runtime, and setting up an HTTP GET endpoint at /hello. LANGUAGE: yaml CODE: service: counter-api frameworkVersion: '3' provider: name: aws runtime: java17 package: artifact: target/hello-dev.jar functions: hello: handler: com.serverless.Handler events: - httpApi: path: /hello method: get ---------------------------------------- TITLE: Using Redis SPOP Command - Multiple Elements Removal DESCRIPTION: Shows how to use SPOP with a count parameter to remove multiple random elements at once. The example demonstrates adding elements to a set and removing two random elements. LANGUAGE: python CODE: redis.sadd("myset", "one", "two", "three") assert redis.spop("myset", 2) in {"one", "two", "three"} ---------------------------------------- TITLE: Removing Members from Redis Sorted Set with ZREM in TypeScript DESCRIPTION: Examples of using the ZREM command to remove members from a Redis sorted set. The command returns the number of members that were removed from the sorted set. The first example shows removing a single member, while the second demonstrates removing multiple members. LANGUAGE: typescript CODE: await redis.zrem("key", "member"); LANGUAGE: typescript CODE: await redis.zrem("key", "member1", "member2"); ---------------------------------------- TITLE: Creating a Node.js Express Application with Upstash Redis DESCRIPTION: This code creates a simple Express application that uses Upstash Redis to implement a page view counter. It demonstrates connecting to Redis, incrementing a counter, and serving the value via an HTTP endpoint. LANGUAGE: javascript CODE: // Note: if you are using Node.js version 17 or lower, // change the first line to the following: // const { Redis } = require ("@upstash/redis/with-fetch"); const { Redis } = require("@upstash/redis"); const express = require("express"); const app = express(); const redis = Redis.fromEnv(); app.get("/", async (req, res) => { const value = await redis.get("counter"); await redis.set("counter", parseInt(value || 0) + 1); res.send(`Counter: ${value || 0}`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); ---------------------------------------- TITLE: Iterating Over Hash Fields Using HSCAN in Python DESCRIPTION: This code snippet demonstrates how to use the HSCAN command to retrieve all members of a hash in Redis. It uses a while loop to continue scanning until the cursor returns 0, indicating the end of the iteration. LANGUAGE: python CODE: # Get all members of a hash. cursor = 0 results = [] while True: cursor, keys = redis.hscan("myhash", cursor, match="*") results.extend(keys) if cursor == 0: break ---------------------------------------- TITLE: Removing Elements by Rank from Redis Sorted Set in TypeScript DESCRIPTION: This code snippet demonstrates how to use the ZREMRANGEBYRANK command in Redis to remove elements from a sorted set based on their rank. It removes all members with ranks between 4 and 20 (inclusive) from the sorted set with the key 'key'. LANGUAGE: typescript CODE: await redis.zremrangebyrank("key", 4, 20) ---------------------------------------- TITLE: Using JSON.STRLEN to Get Length of JSON String in Redis with Python DESCRIPTION: Example of using the Redis JSON.STRLEN command to get the length of a JSON string at a specific path. This command takes a key and a path parameter, returning the length of the string found at that path. LANGUAGE: python CODE: redis.json.strlen("key", "$.path.to.str") ---------------------------------------- TITLE: Retrieving Set Members with SMEMBERS in Redis using Python DESCRIPTION: This example demonstrates how to add elements to a Redis set and then retrieve all members using the SMEMBERS command. The code first adds three values to a set and then verifies that SMEMBERS returns all three elements. LANGUAGE: python CODE: redis.sadd("set", "a", "b", "c"); assert redis.smembers("set") == {"a", "b", "c"} ---------------------------------------- TITLE: Deploying to Koyeb using CLI DESCRIPTION: This command uses the Koyeb CLI to deploy the application. It specifies the GitHub repository, branch, port configurations, and sets the necessary environment variables for the Upstash Redis connection. LANGUAGE: bash CODE: koyeb app init example-koyeb-upstash \ --git github.com// \ --git-branch main \ --ports 3000:http \ --routes /:3000 \ --env PORT=3000 \ --env UPSTASH_REDIS_REST_URL="" \ --env UPSTASH_REDIS_REST_TOKEN="" ---------------------------------------- TITLE: Creating Upstash Developer API Key using Access Token DESCRIPTION: This cURL command shows how to create a Developer API key for Upstash using the access token obtained from the OAuth 2.0 flow. It specifies a custom name for the API key. LANGUAGE: bash CODE: curl https://api.upstash.com/apikey -H "Authorization: Bearer JWT_KEY" -d '{ "name" : "APPNAME_API_KEY_TIMESTAMP" }' ---------------------------------------- TITLE: Using STRLEN to Get String Length in Redis with Python DESCRIPTION: This example demonstrates setting a string value with 'set' command and then using 'strlen' to retrieve its length. It shows that the length of 'Hello World' is 11 characters. LANGUAGE: python CODE: redis.set("key", "Hello World") assert redis.strlen("key") == 11 ---------------------------------------- TITLE: Remove Elements by Lexicographical Range in Redis Sorted Set DESCRIPTION: Demonstrates how to remove elements from a Redis sorted set that fall between two lexicographical values. The command returns the number of elements that were removed from the set. The example shows removing elements between 'alpha' and 'omega' from a sorted set with key 'key'. LANGUAGE: typescript CODE: await redis.zremrangebylex("key", "alpha", "omega") ---------------------------------------- TITLE: Implementing Ephemeral Caching for Rate Limiting in TypeScript DESCRIPTION: This snippet demonstrates how to use an ephemeral in-memory cache for rate limiting to reduce Redis calls and improve performance during high load or DoS attacks. LANGUAGE: typescript CODE: const cache = new Map(); // must be outside of your serverless function handler // ... const ratelimit = new Ratelimit({ // ... ephemeralCache: cache, }); ---------------------------------------- TITLE: Retrieving Hash Field Names with Redis HKEYS in Python DESCRIPTION: Demonstrates how to set hash fields using HSET and retrieve field names using HKEYS. The example shows setting multiple fields in a hash and then retrieving their names as a list. LANGUAGE: python CODE: redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hkeys("myhash") == ["field1", "field2"] ---------------------------------------- TITLE: Decrementing Integer Value with DECR Command in Python DESCRIPTION: This snippet demonstrates how to use the DECR command in Redis to decrement the integer value of a key. It first sets a key with an initial value, then decrements it and asserts the result. LANGUAGE: python CODE: redis.set("key", 6) assert redis.decr("key") == 5 ---------------------------------------- TITLE: Publishing Messages to Redis Channels in TypeScript DESCRIPTION: Example of publishing a message to a Redis channel and getting the number of clients who received it. The method returns an integer representing the number of subscribers who received the message. LANGUAGE: typescript CODE: const listeners = await redis.publish("my-topic", "my-message"); ---------------------------------------- TITLE: Removing Members from a Redis Sorted Set DESCRIPTION: This snippet demonstrates how to use the ZREM command to remove members from a Redis sorted set. It first adds three members to a sorted set called 'myset', then removes one member ('one') and attempts to remove a non-existent member ('four'). The command returns 1, indicating that only one member was successfully removed. LANGUAGE: python CODE: redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zrem("myset", "one", "four") == 1 ---------------------------------------- TITLE: Pipelining Multiple Redis Commands in a Single Request DESCRIPTION: Example of using the /pipeline endpoint to send multiple Redis commands in a single HTTP request. The response contains results for each command in the same order. LANGUAGE: shell CODE: curl -X POST https://us1-merry-cat-32748.upstash.io/pipeline \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -d ' [ ["SET", "key1", "valuex"], ["SETEX", "key2", 13, "valuez"], ["INCR", "key1"], ["ZADD", "myset", 11, "item1", 22, "item2"] ] ' ---------------------------------------- TITLE: Executing ECHO Command in Upstash Redis using Python DESCRIPTION: This code snippet demonstrates how to use the ECHO command in Upstash Redis. It sends a message to the server and asserts that the returned message is the same as the one sent. This is useful for debugging the connection to the Redis server. LANGUAGE: python CODE: assert redis.echo("hello world") == "hello world" ---------------------------------------- TITLE: Moving a Member Between Sets with SMOVE in Redis using TypeScript DESCRIPTION: This example demonstrates how to use the SMOVE command in Redis to move a member from one set to another. It first adds members to an 'original' set, then moves one member to a 'destination' set. LANGUAGE: typescript CODE: await redis.sadd("original", "a", "b", "c"); const moved = await redis.smove("original", "destination", "a"); // moved: 1 // original: ["b", "c"] // destination: ["a"] ---------------------------------------- TITLE: Counting Keys in Redis Database using DBSIZE Command in TypeScript DESCRIPTION: This snippet demonstrates how to use the DBSIZE command to count the number of keys in a Redis database. It uses an asynchronous function call and logs the result to the console. LANGUAGE: typescript CODE: const keys = await redis.dbsize(); console.log(keys) // 20 ---------------------------------------- TITLE: Setting Multiple Redis Keys Using MSET Command in TypeScript DESCRIPTION: Demonstrates how to use the MSET command to set multiple key-value pairs of different types atomically. The example shows setting numeric, string, and object values in a single operation. The command returns 'OK' on successful execution and counts as a single command for billing purposes. LANGUAGE: typescript CODE: await redis.mset({ key1: 1, key2: "hello", key3: { a: 1, b: "hello" }, }); ---------------------------------------- TITLE: Finding Set Intersection with SINTER in Redis (Python) DESCRIPTION: This example demonstrates how to use the SINTER command to find the intersection between two Redis sets. It first creates two sets with some overlapping elements, then uses the SINTER command to identify the common element. LANGUAGE: python CODE: redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sinter("set1", "set2") == {"c"} ---------------------------------------- TITLE: Checking Redis Key TTL in Python DESCRIPTION: Example demonstrating how to check TTL (Time To Live) of Redis keys using Python. Shows setting a key, checking its TTL before and after setting expiration, and checking TTL for non-existent keys. LANGUAGE: python CODE: # Get the TTL of a key redis.set("my-key", "value") assert redis.ttl("my-key") == -1 redis.expire("my-key", 10) assert redis.ttl("my-key") > 0 # Non existent key assert redis.ttl("non-existent-key") == -2 ---------------------------------------- TITLE: Iteratively Scanning Set Members with SSCAN in Python DESCRIPTION: This code demonstrates how to use the SSCAN command to retrieve all members of a Redis set. It iterates through the set using a cursor-based approach, continuing until the cursor returns 0, which indicates the iteration is complete. LANGUAGE: python CODE: # Get all members of a set. cursor = 0 results = set() while True: cursor, keys = redis.sscan("myset", cursor, match="*") results.extend(keys) if cursor == 0: break ---------------------------------------- TITLE: Appending Values to JSON Array in Redis using JSON.ARRAPPEND DESCRIPTION: This example demonstrates how to append a string value to an array located at a specific path within a JSON document stored in Redis. The command returns the new length of the array after appending. LANGUAGE: typescript CODE: await redis.json.arrappend("key", "$.path.to.array", "a"); ---------------------------------------- TITLE: Removing Multiple Members from Redis Set using SREM DESCRIPTION: Example showing how to remove multiple members from a Redis set using SREM command. First adds three members to a set using SADD, then removes two existing members and one non-existing member. Returns the count of successfully removed members. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const removed = await redis.srem("set", "a", "b", "d"); console.log(removed); // 2 ---------------------------------------- TITLE: Using LPUSHX Command in Redis with Python DESCRIPTION: This example demonstrates how to use the LPUSHX command in Redis with Python. It first initializes a list with an element, then uses LPUSHX to add more elements to an existing list, and finally shows that LPUSHX returns 0 when used on a non-existent list. LANGUAGE: python CODE: # Initialize the list redis.lpush("mylist", "one") assert redis.lpushx("mylist", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] # Non existing key assert redis.lpushx("non-existent-list", "one") == 0 ---------------------------------------- TITLE: Setting Up Redis Environment Variables DESCRIPTION: Exports the Upstash Redis connection details as environment variables for use in the Lambda function. LANGUAGE: shell CODE: export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Implementing Voting API in Next.js DESCRIPTION: This serverless API function updates (increments) the score of the selected feature request in Redis. It also tracks IP addresses to prevent multiple votes on the same feature request. LANGUAGE: javascript CODE: import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; let ip = req.headers["x-forwarded-for"] || req.headers["Remote_Addr"] || "NA"; let c = ip === "NA" ? 1 : await redis.sadd("s:" + title, ip); if (c === 0) { redis.quit(); res.json({ error: "You can not vote an item multiple times", }); } else { let v = await redis.zincrby("roadmap", 1, title); redis.quit(); res.json({ body: v, }); } }; ---------------------------------------- TITLE: Setting Multiple Redis Keys Using MSET in Python DESCRIPTION: Example of using the MSET command to set multiple key-value pairs in Redis simultaneously. Takes a dictionary of key-value pairs and returns True on success. This operation counts as a single command for billing purposes. LANGUAGE: python CODE: redis.mset({ "key1": "value1", "key2": "value2" }) ---------------------------------------- TITLE: Loading and Executing Lua Script in Redis with Python DESCRIPTION: Demonstrates how to load a Lua script into Redis's script cache using script_load() and then execute it using evalsha(). The example loads a simple script that returns 1 and verifies its execution. LANGUAGE: python CODE: sha1 = redis.script_load("return 1") assert redis.evalsha(sha1) == 1 ---------------------------------------- TITLE: Attempting RPUSHX on a Non-Existent List in Redis using TypeScript DESCRIPTION: This example shows the behavior of RPUSHX when the specified list doesn't exist. When attempting to push to a non-existent list, RPUSHX returns 0 and doesn't create the list. LANGUAGE: typescript CODE: const length = await redis.rpushx("key", "a"); console.log(length); // 0 ---------------------------------------- TITLE: Retrieving JSON String Length in Redis using TypeScript DESCRIPTION: This snippet demonstrates how to use the JSON.STRLEN command in Redis to get the length of a JSON String at a specific path within a key. It uses the redis client's json.strlen method with the key, path, and an additional parameter. LANGUAGE: typescript CODE: await redis.json.strlen("key", "$.path.to.str", "a"); ---------------------------------------- TITLE: Using HSETNX Command in Upstash Redis with TypeScript DESCRIPTION: This example demonstrates how to use the HSETNX command to set a field in a hash only if it doesn't already exist. The command takes a key, field name, and value as arguments. It returns 1 if the field was set, or 0 if it already existed. LANGUAGE: typescript CODE: await redis.hsetnx("key", "id", 1) ---------------------------------------- TITLE: Redis Cache Configuration DESCRIPTION: Environment variables setup for Redis cache driver LANGUAGE: shell CODE: CACHE_STORE="redis" REDIS_CACHE_DB="0" ---------------------------------------- TITLE: Using MGET Command in Python to Retrieve Multiple Redis Keys DESCRIPTION: This snippet demonstrates how to use the MGET command to retrieve multiple keys from Redis in a single operation. It first sets two keys with their values, then retrieves both keys simultaneously using the mget method and verifies the returned values. LANGUAGE: python CODE: redis.set("key1", "value1") redis.set("key2", "value2") assert redis.mget("key1", "key2") == ["value1", "value2"] ---------------------------------------- TITLE: Configuring Upstash Redis Environment Variables DESCRIPTION: Example of setting up the Upstash Redis connection details in the .env file. These environment variables are used to connect to the Redis database. LANGUAGE: shell CODE: UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Implementing FastAPI with Upstash Redis Counter DESCRIPTION: FastAPI application implementation that uses Upstash Redis to create an incrementing counter endpoint. LANGUAGE: python CODE: from fastapi import FastAPI from upstash_redis import Redis app = FastAPI() redis = Redis.from_env() @app.get("/") def read_root(): count = redis.incr('counter') return {"count": count} ---------------------------------------- TITLE: Getting Key Type in Redis using TypeScript DESCRIPTION: Example showing how to check the data type of a Redis key. First sets a string value, then retrieves its type which returns 'string'. LANGUAGE: typescript CODE: await redis.set("key", "value"); const t = await redis.type("key"); console.log(t) // "string" ---------------------------------------- TITLE: Searching for Value in JSON Array with JSON.ARRINDEX in Python DESCRIPTION: This example demonstrates how to use the JSON.ARRINDEX command to search for the first occurrence of a value in a JSON array stored in Redis. It returns the index of the first occurrence or -1 if not found. LANGUAGE: python CODE: index = redis.json.arrindex("key", "$.path.to.array", "a") ---------------------------------------- TITLE: Removing Lowest Scored Members from Redis Sorted Set using ZPOPMIN DESCRIPTION: This example demonstrates how to use the ZPOPMIN command in Redis. It first adds members to a sorted set 'myset' with different scores, then uses zpopmin to remove and return the member with the lowest score. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmin("myset") == [("a", 1)] ---------------------------------------- TITLE: Setting Key Expiration with PEXPIREAT in Redis using Python DESCRIPTION: Examples of setting key expiration with PEXPIREAT using both a Unix timestamp in milliseconds and a datetime object. The first example uses the current time multiplied by 1000 to convert to milliseconds, while the second uses a datetime object with a 5-second offset. LANGUAGE: python CODE: # With a unix timestamp redis.set("mykey", "Hello") redis.pexpireat("mykey", int(time.time() * 1000) ) # With a datetime object redis.set("mykey", "Hello") redis.pexpireat("mykey", datetime.datetime.now() + datetime.timedelta(seconds=5)) ---------------------------------------- TITLE: Updating Last Access Time for Multiple Redis Keys using TOUCH Command DESCRIPTION: This example demonstrates how to use the TOUCH command to update the last access time of multiple Redis keys. The command takes one or more key names as arguments and returns the number of keys that were successfully touched. LANGUAGE: typescript CODE: await redis.touch("key1", "key2", "key3"); ---------------------------------------- TITLE: LPOS Command with Rank Parameter in Redis DESCRIPTION: Shows how to use the LPOS command with the rank parameter to find the position of a specific occurrence of an element. Finds the second occurrence of element 'b' in the list. LANGUAGE: typescript CODE: await redis.rpush("key", "a", "b", "c", "b"); const index = await redis.lpos("key", "b", { rank: 2 }); console.log(index); // 3 ---------------------------------------- TITLE: Performing Set Union and Storing Result with Redis in Python DESCRIPTION: This code snippet demonstrates how to use the SUNIONSTORE command in Redis using Python. It first adds elements to two sets, then performs a union operation and stores the result in a new set. LANGUAGE: python CODE: redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); redis.sunionstore("destination", "set1", "set2") ---------------------------------------- TITLE: Environment Configuration for Upstash Redis DESCRIPTION: Environment variable configuration for Upstash Redis connection credentials. LANGUAGE: shell CODE: UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Remove Elements by Score Range in Redis Sorted Set using Python DESCRIPTION: Demonstrates how to remove members from a Redis sorted set where their scores fall between specified minimum and maximum values. The command returns the number of elements that were removed from the set. LANGUAGE: python CODE: redis.zremrangebyscore("key", 2, 5) ---------------------------------------- TITLE: Setting Key Expiration in Milliseconds with Redis PEXPIRE Command (TypeScript) DESCRIPTION: This code snippet demonstrates how to use the PEXPIRE command in Redis to set a key's expiration time in milliseconds. The example sets a 1-minute (60,000 milliseconds) expiration on a key. LANGUAGE: typescript CODE: await redis.pexpire(key, 60_000); // 1 minute ---------------------------------------- TITLE: Appending Strings to JSON Path in Redis using JSON.STRAPPEND DESCRIPTION: Example of using the JSON.STRAPPEND command to append a string value to an existing string at a specified JSON path. This command takes a key, a path to the target string, and the value to append, returning the new length of the string after appending. LANGUAGE: python CODE: redis.json.strappend("key", "$.path.to.str", "abc") ---------------------------------------- TITLE: Executing Read-Only Lua Script in Redis using Python DESCRIPTION: This example demonstrates how to use the eval_ro method to execute a read-only Lua script in Redis. The script retrieves a value from a key and returns it. The example also shows how to set a key before executing the script. LANGUAGE: python CODE: script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval_ro(script, keys=["mykey"]) == "Hello" ---------------------------------------- TITLE: Retrieving and Deleting a Key-Value Pair in Redis using Python DESCRIPTION: This snippet demonstrates the usage of the GETDEL command in Redis using Python. It sets a key-value pair, retrieves the value while deleting the key, and then verifies that the key no longer exists. LANGUAGE: python CODE: redis.set("key", "value") assert redis.getdel("key") == "value" assert redis.get("key") == None ---------------------------------------- TITLE: Appending Values to Array in JSON Document with Redis Python Client DESCRIPTION: Example of using the JSON.ARRAPPEND command with the Redis Python client to append a string value to an array at a specific path within a JSON document. The command returns the new length of the array after appending. LANGUAGE: python CODE: redis.json.arrappend("key", "$.path.to.array", "a") ---------------------------------------- TITLE: Setting Multiple JSON Values in Redis using Python DESCRIPTION: This snippet demonstrates how to use the json.set method to set multiple JSON values at different paths in multiple keys. It uses a list of tuples, where each tuple contains a key, a path, and a value. LANGUAGE: python CODE: redis.json.set([(key, "$.path", value), (key2, "$.path2", value2)]) ---------------------------------------- TITLE: Setting Conditional Hash Fields with Redis HSETNX DESCRIPTION: Example demonstrating how to use HSETNX to set a hash field only if it doesn't exist. The first operation succeeds because the field doesn't exist, while the second fails because the field was already set. LANGUAGE: python CODE: assert redis.hsetnx("myhash", "field1", "Hello") == True assert redis.hsetnx("myhash", "field1", "World") == False ---------------------------------------- TITLE: SET Command in Redis (TypeScript) DESCRIPTION: Placeholder for the SET command in Redis. This command is used to set the string value of a key. LANGUAGE: typescript CODE: ---------------------------------------- TITLE: Implementing Rate Limiting Logic in AWS Lambda Handler DESCRIPTION: JavaScript implementation of a Lambda function handler that uses @upstash/ratelimit to limit requests based on client IP addresses, allowing 10 requests per 10 seconds using a sliding window algorithm. LANGUAGE: js CODE: const { Ratelimit } = require("@upstash/ratelimit"); const { Redis } = require("@upstash/redis"); const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), prefix: "@upstash/ratelimit", analytics: true, }); exports.ratelimit = async (event) => { const identifier = event.requestContext.http.sourceIP; const { success, limit, remaining, pending } = await ratelimit.limit( identifier ); const response = { success: success, limit: limit, remaining: remaining, }; // pending is a promise for handling the analytics submission await pending; if (!success) { return { statusCode: 429, body: JSON.stringify(response), }; } return { statusCode: 200, body: JSON.stringify(response), }; }; ---------------------------------------- TITLE: Retrieving Element from Redis List using LINDEX in TypeScript DESCRIPTION: This example demonstrates how to use the LINDEX command to retrieve an element from a Redis list. It first pushes elements to a list using RPUSH, then retrieves the element at index 0 using LINDEX. LANGUAGE: typescript CODE: await redis.rpush("key", "a", "b", "c"); const element = await redis.lindex("key", 0); console.log(element); // "a" ---------------------------------------- TITLE: Configuring Redis Retry Settings in TypeScript DESCRIPTION: Example showing how to customize retry settings when initializing the Redis client. Demonstrates setting custom retry count and backoff function for handling network errors. LANGUAGE: typescript CODE: new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN, retry: { retries: 5, backoff: (retryCount) => Math.exp(retryCount) * 50, }, }); ---------------------------------------- TITLE: Executing Custom Redis Commands in Python DESCRIPTION: Shows how to execute custom Redis commands that haven't been implemented in the client library by using the execute function and passing the command as a list. LANGUAGE: python CODE: redis.execute(["XLEN", "test_stream"]) ---------------------------------------- TITLE: Scanning Redis Database for Keys using TypeScript DESCRIPTION: This snippet demonstrates how to use the SCAN command to retrieve keys from a Redis database. It uses a cursor starting at 0 and a pattern to match all keys. LANGUAGE: typescript CODE: const [cursor, keys] = await redis.scan(0, { match: "*" }); ---------------------------------------- TITLE: Retrieving Typed Values with Redis GET Command in TypeScript DESCRIPTION: Demonstrates how to fetch a strongly-typed value from Redis using the GET command with TypeScript generics. Includes null checking and type safety for the retrieved value. LANGUAGE: typescript CODE: type MyType = { a: number; b: string; } const value = await redis.get("key"); if (!value) { // key doesn't exist } else { // value is of type MyType } ---------------------------------------- TITLE: Multiplying JSON Number Values with Redis JSON.NUMMULTBY DESCRIPTION: Example showing how to multiply a numeric value in a JSON document stored in Redis. The command takes a key, JSON path, and multiplication factor as arguments and returns the new value after multiplication. LANGUAGE: typescript CODE: const newValue = await redis.json.nummultby("key", "$.path.to.value", 2); ---------------------------------------- TITLE: Executing ZDIFFSTORE Command in Redis using TypeScript DESCRIPTION: This snippet demonstrates how to use the ZDIFFSTORE command in Redis using TypeScript. It writes the difference between two sorted sets to a new key and returns the number of elements in the resulting set. LANGUAGE: typescript CODE: const values = await redis.zdiffstore("destination", 2, "key1", "key2"); ---------------------------------------- TITLE: SETNX Command in Redis (TypeScript) DESCRIPTION: Placeholder for the SETNX command in Redis. This command sets the value of a key, only if the key does not exist. LANGUAGE: typescript CODE: ---------------------------------------- TITLE: Using ZRANGE with withScores Option in Redis DESCRIPTION: Example showing how to retrieve elements from a sorted set along with their scores. The withScores option returns an interleaved array of members and their corresponding scores. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, ) const res = await redis.zrange("key", 1, 3, { withScores: true }) console.log(res) // ["m2", 2] ---------------------------------------- TITLE: Retrieving Hash Field Value with HGET in TypeScript DESCRIPTION: This example demonstrates how to use the HGET command to retrieve the value of a hash field. It first sets a hash field using HSET, then retrieves the value using HGET, and finally logs the result. LANGUAGE: typescript CODE: await redis.hset("key", {field: "value"}); const field = await redis.hget("key", "field"); console.log(field); // "value" ---------------------------------------- TITLE: Inserting Values into JSON Array with Redis DESCRIPTION: Demonstrates how to use the json.arrinsert method to insert multiple values into a JSON array at a specified index. The method takes a key, path to the array, index position, and one or more values to insert. Returns the new length of the array after insertion. LANGUAGE: typescript CODE: const length = await redis.json.arrinsert("key", "$.path.to.array", 2, "a", "b"); ---------------------------------------- TITLE: Performing Simple Set Intersection with ZINTER in Redis using Python DESCRIPTION: This snippet demonstrates how to use the ZINTER command to find the intersection of two sorted sets in Redis. It adds elements to two sets and then performs an intersection operation. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zinter(["key1", "key2"]) assert result == ["c"] ---------------------------------------- TITLE: Conditional Key Update in Redis DESCRIPTION: Sets a key-value pair only if the key already exists using the 'xx' option. LANGUAGE: typescript CODE: await redis.set("my-key", {my: "value"}, { xx: true }); ---------------------------------------- TITLE: Counting Sorted Set Elements with Score Range in Python DESCRIPTION: Example demonstrating how to use the ZCOUNT command to count elements in a Redis sorted set within a specified score range. The example adds two elements to a sorted set and counts elements with scores greater than 1. LANGUAGE: python CODE: redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ) elements = redis.zcount("key", "(1", "+inf") print(elements); # 1 ---------------------------------------- TITLE: Retrieving Multiple Random Fields from Redis Hash - Python DESCRIPTION: Shows how to retrieve multiple random fields from a hash using the count parameter. Returns an array of two field names in random order. LANGUAGE: python CODE: redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash", count=2) in [ ["field1", "field2"], ["field2", "field1"] ] ---------------------------------------- TITLE: Retrieving Member Ranks Using ZRANK in Python DESCRIPTION: Example demonstrates using the ZRANK command to get member rankings in a Redis sorted set. First adds members with scores to a sorted set 'myset', then retrieves their ranks where rank 0 is the lowest score. Shows handling of both existing and non-existing members. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrank("myset", "a") == 0 assert redis.zrank("myset", "d") == None assert redis.zrank("myset", "b") == 1 assert redis.zrank("myset", "c") == 2 ---------------------------------------- TITLE: Creating Upstash Redis Database using API DESCRIPTION: This cURL command demonstrates how to create a new Redis database using the Upstash API. It includes parameters for database name, region, primary region, read regions, and TLS configuration. LANGUAGE: bash CODE: curl -X POST \ https://api.upstash.com/v2/redis/database \ -u 'EMAIL:API_KEY' \ -d '{"name":"myredis", "region":"global", "primary_region":"us-east-1", "read_regions":["us-west-1","us-west-2"], "tls": true}' ---------------------------------------- TITLE: Using SDIFF Command to Find Set Difference in Redis with TypeScript DESCRIPTION: This snippet demonstrates how to use the Redis SDIFF command to find the difference between two sets. It first adds elements to two different sets using SADD, then retrieves the elements that are in the first set but not in the second set using SDIFF. LANGUAGE: typescript CODE: await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const diff = await redis.sdiff("set1", "set2"); console.log(diff); // ["a", "b"] ---------------------------------------- TITLE: Executing Lua Script with EVAL Command in TypeScript DESCRIPTION: Example showing how to execute a simple Lua script using Redis EVAL command. The script returns the first argument passed to it, demonstrating basic argument passing and script execution. LANGUAGE: typescript CODE: const script = ` return ARGV[1] ` const result = await redis.eval(script, [], ["hello"]); console.log(result) // "hello" ---------------------------------------- TITLE: Counting Set Bits with BITCOUNT in Redis using TypeScript DESCRIPTION: This snippet demonstrates how to use the BITCOUNT command in Redis to count the number of set bits in a binary string. It shows two examples: one for counting all set bits in a key, and another for counting set bits within a specified range. LANGUAGE: typescript CODE: const bits = await redis.bitcount(key); LANGUAGE: typescript CODE: const bits = await redis.bitcount(key, 5, 10); ---------------------------------------- TITLE: Using HMGET to Retrieve Multiple Hash Fields in Python DESCRIPTION: This example demonstrates how to set multiple fields in a hash using HSET and then retrieve those fields using HMGET. The command returns the values of the specified fields in the same order as requested. LANGUAGE: python CODE: redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hmget("myhash", "field1", "field2") == ["Hello", "World"] ---------------------------------------- TITLE: Decrementing Integer Values Using Redis DECRBY in Python DESCRIPTION: Example of setting a key with an integer value and then decrementing it by a specific amount using the decrby method. The example sets 'key' to value 6, then decrements it by 4, resulting in a final value of 2. LANGUAGE: python CODE: redis.set("key", 6) assert redis.decrby("key", 4) == 2 ---------------------------------------- TITLE: Moving Elements Between Redis Lists using LMOVE DESCRIPTION: Example demonstrates pushing elements to a source list and then moving an element from the source list to a destination list. The operation shows how to first populate a list with RPUSH and then use LMOVE to transfer an element. LANGUAGE: typescript CODE: await redis.rpush("source", "a", "b", "c"); const element = await redis.move("source", "destination", "left", "left"); ---------------------------------------- TITLE: Using SCARD Command with Redis in TypeScript DESCRIPTION: This example demonstrates how to use the SCARD command to get the cardinality of a Redis set. It first adds members to a set using SADD, then uses SCARD to count the members. LANGUAGE: typescript CODE: await redis.sadd("key", "a", "b", "c"); const cardinality = await redis.scard("key"); console.log(cardinality); // 3 ---------------------------------------- TITLE: Defining Python Dependencies DESCRIPTION: Creates a requirements.txt file to specify the Upstash Redis dependency for the Python Lambda function. LANGUAGE: txt CODE: upstash-redis ---------------------------------------- TITLE: Implementing Redis Counter in Next.js API Route DESCRIPTION: TypeScript code for a Next.js API route that uses Upstash Redis to increment and return a counter value. It demonstrates initialization of the Redis client and handling of API requests. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; import type { NextApiRequest, NextApiResponse } from "next"; const redis = Redis.fromEnv(); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const count = await redis.incr("counter"); res.status(200).json({ count }); } ---------------------------------------- TITLE: Incrementing Integer Value of a Key in Redis using TypeScript DESCRIPTION: This example demonstrates how to use the INCR command in Redis to increment the integer value of a key. It first sets a key with an initial value and then increments it. LANGUAGE: typescript CODE: await redis.set("key", 6); await redis.incr("key"); // returns 7 ---------------------------------------- TITLE: Setting Multiple Keys Atomically with MSETNX in Python DESCRIPTION: This snippet demonstrates how to use the MSETNX command to set multiple keys atomically in Redis using Python. It sets key-value pairs only if none of the keys already exist. The method takes a dictionary as an argument where keys are the Redis keys and values are the corresponding values to be set. LANGUAGE: python CODE: redis.msetnx({ key1: 1, key2: "hello", key3: { a: 1, b: "hello" }, }) ---------------------------------------- TITLE: Using ZRANDMEMBER in Redis with Python DESCRIPTION: Demonstrates how to use the ZRANDMEMBER command to retrieve random members from a Redis sorted set. The example first adds elements to a sorted set with their scores, then shows how to retrieve a single random member and multiple random members. LANGUAGE: python CODE: redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) # "one" redis.zrandmember("myset") # ["one", "three"] redis.zrandmember("myset", 2) ---------------------------------------- TITLE: Checking Field Existence in Redis Hash using HEXISTS DESCRIPTION: This example demonstrates how to check if a field exists in a Redis hash. First, it sets a field-value pair in a hash using hset, then verifies the field exists using hexists, which returns True for existing fields. LANGUAGE: python CODE: redis.hset("key", "field", "value") assert redis.hexists("key", "field") == True ---------------------------------------- TITLE: Querying JSON Value Type in Redis using TypeScript DESCRIPTION: This snippet demonstrates how to use the JSON.TYPE command in Redis to get the type of a JSON value at a specific path. It uses an asynchronous function call to retrieve the type. LANGUAGE: typescript CODE: const myType = await redis.json.type("key", "$.path.to.value"); ---------------------------------------- TITLE: Using GETSET Command in Redis with Python DESCRIPTION: This snippet demonstrates how to use the GETSET command in Redis using Python. It sets an initial value, then uses GETSET to retrieve the old value while setting a new one. LANGUAGE: python CODE: redis.set("key", "old-value") assert redis.getset("key", "newvalue") == "old-value" ---------------------------------------- TITLE: Calculating Set Difference with ZDIFF in Redis (Python) DESCRIPTION: This snippet demonstrates the basic usage of the ZDIFF command in Redis using Python. It creates two sorted sets and calculates their difference. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zdiff(["key1", "key2"]) assert result == ["a", "b"] ---------------------------------------- TITLE: Redis Data Storage Command DESCRIPTION: HMSET command to store IoT sensor data in Redis using client ID as key and storing timestamp with temperature values. LANGUAGE: bash CODE: HMSET ${client_id} ${up_timestamp} ${temp} ---------------------------------------- TITLE: Iterating Through Redis Keys Using SCAN Command in Python DESCRIPTION: Example demonstrating how to use the Redis SCAN command to retrieve all keys from the database. The code uses a while loop to iterate through keys using a cursor-based pagination approach until all keys are retrieved. LANGUAGE: python CODE: # Get all keys cursor = 0 results = [] while True: cursor, keys = redis.scan(cursor, match="*") results.extend(keys) if cursor == 0: break ---------------------------------------- TITLE: Executing PING Command in Python DESCRIPTION: Sends a PING command to the Redis server and verifies that it returns 'PONG' as expected. This is commonly used to check server connectivity and responsiveness. LANGUAGE: python CODE: assert redis.ping() == "PONG" ---------------------------------------- TITLE: Executing Cached Lua Script with EVALSHA in Python DESCRIPTION: This snippet demonstrates how to use the EVALSHA command in Python to execute a cached Lua script on the Redis server. It uses the script's SHA1 hash and passes an argument to the script. LANGUAGE: python CODE: result = redis.evalsha("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", args=["hello"]) assert result = "hello" ---------------------------------------- TITLE: Retrieving Key Expiration Time in Milliseconds with Redis PTTL Command in TypeScript DESCRIPTION: This code snippet demonstrates how to use the PTTL command with Redis to get the remaining time-to-live for a key in milliseconds. The command accepts a key string and returns an integer representing the milliseconds until expiration or a negative value if the key doesn't exist or has no expiration. LANGUAGE: typescript CODE: const millis = await redis.pttl(key); ---------------------------------------- TITLE: Iterating Through a Redis Sorted Set Using ZSCAN in Python DESCRIPTION: This example demonstrates how to retrieve all elements of a Redis sorted set using the ZSCAN command with cursor-based pagination. The code iterates until the cursor returns 0 (indicating completion) and collects all key-score pairs from the sorted set. LANGUAGE: python CODE: # Get all elements of an ordered set. cursor = 0 results = [] while True: cursor, keys = redis.zscan("myzset", cursor, match="*") results.extend(keys) if cursor == 0: break for key, score in results: print(key, score) ---------------------------------------- TITLE: Decrementing Integer Value Using Redis DECR Command in TypeScript DESCRIPTION: Demonstrates how to decrement an integer value stored in Redis using the DECR command. First sets a key with value 6, then decrements it to 5. LANGUAGE: typescript CODE: await redis.set("key", 6); await redis.decr("key"); // returns 5 ---------------------------------------- TITLE: Incrementing Hash Field Value with HINCRBYFLOAT in TypeScript DESCRIPTION: Example showing how to increment a hash field value by a float number using Redis. First sets an initial value using HSET, then increments it by 2.5 using HINCRBYFLOAT. LANGUAGE: typescript CODE: await redis.hset("key", { field: 20, }); const after = await redis.hincrby("key", "field", 2.5); console.log(after); // 22.5 ---------------------------------------- TITLE: Simple Redis ZINTER Operation DESCRIPTION: Demonstrates basic usage of Redis ZINTER command by creating two sorted sets and finding their intersection without additional parameters. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zunion(["key1", "key2"]) assert result == ["a", "b", "c", "d", "e"] ---------------------------------------- TITLE: MSETNX Command in Redis (TypeScript) DESCRIPTION: Placeholder for the MSETNX command in Redis. The command is typically used to set multiple keys to multiple values, only if none of the keys already exist. LANGUAGE: typescript CODE: ---------------------------------------- TITLE: Deleting Multiple Hash Fields with HDEL in TypeScript DESCRIPTION: This example demonstrates how to use the HDEL command to delete multiple fields from a Redis hash. The command returns the number of fields that were removed from the hash. LANGUAGE: typescript CODE: await redis.hdel(key, 'field1', 'field2'); // returns 5 ---------------------------------------- TITLE: Redis ZINTER with Aggregation DESCRIPTION: Shows how to use ZINTER with score aggregation, combining scores from multiple sets using the SUM aggregation function and returning scores with results. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ---------------------------------------- TITLE: Using PTTL to Check Key Expiration Time in Redis with Python DESCRIPTION: This example demonstrates how to use the PTTL command in Redis. It sets a key, verifies it has no expiration initially, sets an expiration time, confirms the expiration is set, and finally removes the expiration. LANGUAGE: python CODE: redis.set("key1", "Hello") assert redis.pttl("key1") == -1 redis.expire("key1", 1000) assert redis.pttl("key1") > 0 redis.persist("key1") assert redis.pttl("key1") == -1 ---------------------------------------- TITLE: Deleting JSON Path Using Redis JSON.FORGET Command - Python DESCRIPTION: Demonstrates how to use the JSON.FORGET command to delete a specific path from a JSON document stored in Redis. The command returns the number of paths that were deleted. LANGUAGE: python CODE: redis.json.forget("key", "$.path.to.value") ---------------------------------------- TITLE: Basic Redis Operations in Laravel DESCRIPTION: Example of basic Redis operations using Laravel's Redis Facade for storing and retrieving values. LANGUAGE: php CODE: use Illuminate\Support\Facades\Redis; // Storing a value in Redis Redis::set('key', 'value'); // Retrieving a value from Redis $value = Redis::get('key'); ---------------------------------------- TITLE: Using SETRANGE Command in Python with Redis DESCRIPTION: Demonstrates how to use the SETRANGE command to modify a string value at a specific offset. The example shows setting an initial string 'Hello World', then replacing 'World' with 'Redis' starting at offset 6, resulting in 'Hello Redis'. LANGUAGE: python CODE: redis.set("key", "Hello World") assert redis.setrange("key", 6, "Redis") == 11 assert redis.get("key") == "Hello Redis" ---------------------------------------- TITLE: Weather Data Processing and Route Handler in Elixir DESCRIPTION: Main route handler and helper method for processing weather data. Includes response rendering and data structure transformation. LANGUAGE: elixir CODE: def home(conn, %{"text" => text}) do case fetch_weather(text) do {:ok, %{"location" => location, "temp" => temp_c, "condition" => condition_text}} -> render_home(conn, %Payload{weather: "#{condition_text}, #{temp_c}", location: location}) {:error, reason} -> render_home(conn, %Payload{text: reason}) end end defp get_weather_info(%{ "location" => %{ "name" => name, "region" => region }, "current" => %{ "temp_c" => temp_c, "condition" => %{ "text" => condition_text } } }) do %{"location" => "#{name}, #{region}", "temp" => temp_c, "condition" => condition_text} end ---------------------------------------- TITLE: Error Response Formats from Upstash Redis REST API DESCRIPTION: Examples of error responses from the REST API. Errors are returned with an 'error' field containing a description of what went wrong. LANGUAGE: json CODE: {"error":"WRONGPASS invalid password"} LANGUAGE: json CODE: {"error":"ERR wrong number of arguments for 'get' command"} ---------------------------------------- TITLE: Adding Multiple Members to Redis Sorted Set (TypeScript) DESCRIPTION: This snippet demonstrates how to add multiple members to a Redis sorted set using the ZADD command. It adds two members with their respective scores to the specified key. LANGUAGE: typescript CODE: await redis.zadd( "key", { score: 2, member: "member" }, { score: 3, member: "member2"}, ); ---------------------------------------- TITLE: Initializing Redis Client with Auto-Pipelining Using Constructor DESCRIPTION: Creates a Redis client with auto-pipelining enabled by directly providing the connection URL and token. This approach requires manually specifying the Upstash Redis REST URL and token instead of using environment variables. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; const redis = new Redis({ url: , token: , enableAutoPipelining: true }) ---------------------------------------- TITLE: Retrieving List Elements with LRANGE in Redis using Python DESCRIPTION: This example demonstrates how to use the LRANGE command to retrieve elements from a Redis list. It first pushes three elements to a list using RPUSH, then retrieves a subset of elements using LRANGE with both positive indices (0 to 1) and a full list retrieval using negative index (-1). LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.lrange("mylist", 0, 1) == ["one", "two"] assert redis.lrange("mylist", 0, -1) == ["one", "two", "three"] ---------------------------------------- TITLE: Using ZLEXCOUNT to count elements in a Redis sorted set by lexicographical range DESCRIPTION: This example demonstrates how to use the ZLEXCOUNT command to count elements in a sorted set within a specified lexicographical range. It first adds elements to a sorted set using zadd, then uses zlexcount to count elements from 'two' to the maximum possible value ('+'). The result is the count of elements matching the criteria. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zlexcount("key", "two", "+"); console.log(elements); // 1 ---------------------------------------- TITLE: Executing Read-Only Lua Script with Redis EVAL_RO in TypeScript DESCRIPTION: This example demonstrates how to evaluate a read-only Lua script on Redis using the evalRo method. The script simply returns the first argument passed to it, showing the basic syntax for executing server-side Lua scripts. LANGUAGE: ts CODE: const script = ` return ARGV[1] ` const result = await redis.evalRo(script, [], ["hello"]); console.log(result) // "hello" ---------------------------------------- TITLE: Removing Elements by Rank Range from Redis Sorted Set DESCRIPTION: Demonstrates how to remove elements from a Redis sorted set by specifying a range of ranks (positions). The command removes all elements with ranks between 4 and 20 inclusive, returning the number of elements removed. LANGUAGE: python CODE: redis.zremrangebyrank("key", 4, 20) ---------------------------------------- TITLE: ZINTERSTORE with Weights in Redis using Python DESCRIPTION: This snippet demonstrates the use of ZINTERSTORE with custom weights. It intersects two sets, applying different weights to each set before aggregation. The 'SUM' aggregation and 'withscores' option are also used. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zinterstore("dest", ["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == 1 ---------------------------------------- TITLE: Counting Database Keys with DBSIZE in Redis using Python DESCRIPTION: This snippet demonstrates how to use the dbsize() method to count the number of keys in a Redis database. The command takes no arguments and returns an integer representing the total number of keys in the database. LANGUAGE: python CODE: redis.dbsize() ---------------------------------------- TITLE: Requesting Responses in RESP2 Format DESCRIPTION: Examples of setting the Upstash-Response-Format header to request responses in Redis RESP2 binary format instead of JSON, which matches the output format of TCP-based Redis clients. LANGUAGE: shell CODE: curl https://us1-merry-cat-32748.upstash.io/SET/foo/bar \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -H "Upstash-Reponse-Format: resp2" # +OK\r\n curl https://us1-merry-cat-32748.upstash.io/GET/foo \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -H "Upstash-Reponse-Format: resp2" # $3\r\nbar\r\n ---------------------------------------- TITLE: Setting Expiry on Redis Keys with PEXPIRE in Python DESCRIPTION: Examples of using the Redis PEXPIRE command to set expiry timeouts on keys. Shows both using direct millisecond values and datetime.timedelta objects for timeout specification. LANGUAGE: python CODE: # With milliseconds redis.set("mykey", "Hello") redis.expire("mykey", 500) # With a timedelta redis.set("mykey", "Hello") redis.expire("mykey", datetime.timedelta(milliseconds=500)) ---------------------------------------- TITLE: Retrieving Random Hash Fields with Values using Redis HRANDFIELD DESCRIPTION: Example demonstrating how to retrieve random fields along with their values using the withValues parameter. Returns an object containing the selected fields and their corresponding values. LANGUAGE: typescript CODE: await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const randomFields = await redis.hrandfield("key", 2, true); console.log(randomFields); // { id: "1", username: "chronark" } or any other combination ---------------------------------------- TITLE: Simple Redis ZUNIONSTORE Operation in Python DESCRIPTION: Basic example of using zunionstore to combine two sorted sets. Demonstrates adding elements to two sets and computing their union. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zunionstore(["key1", "key2"]) assert result == 5 ---------------------------------------- TITLE: ZSCAN with Count Parameter in TypeScript DESCRIPTION: Shows how to use ZSCAN with both pattern matching and count parameter to limit the number of returned members per iteration. The count parameter controls the number of elements returned in each scan operation. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "a" }, { score: 2, member: "ab" }, { score: 3, member: "b" }, { score: 4, member: "c" }, { score: 5, member: "d" }, ) const [newCursor, members] = await redis.sscan("key", 0, { match: "a*", count: 1}); console.log(newCursor); // likely `0` since this is a very small set console.log(members); // ["a"] ---------------------------------------- TITLE: Popping Multiple Elements from Redis List with LPOP in Python DESCRIPTION: This example shows how to remove and return multiple elements from a Redis list using LPOP with a count parameter. It pushes three elements to a list with RPUSH, then pops the first two elements with LPOP(key, 2). LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.lpop("mylist", 2) == ["one", "two"] ---------------------------------------- TITLE: Using Redis Pipelines in Python Client DESCRIPTION: Demonstrates how to use Redis pipelines to batch multiple commands together, reducing network roundtrips and improving performance when executing multiple operations. LANGUAGE: python CODE: pipeline = redis.pipeline() pipeline.set("foo", 1) pipeline.incr("foo") pipeline.get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ---------------------------------------- TITLE: Clearing Nested JSON Values Using Path in Redis DESCRIPTION: Example of using JSON.CLEAR with a specific path to clear values at a nested location within the JSON document. Uses JSONPath syntax to specify the target location. LANGUAGE: python CODE: redis.json.clear("key", "$.my.key") ---------------------------------------- TITLE: Install Redis Client DESCRIPTION: Command to install the ioredis client as a dependency LANGUAGE: bash CODE: npm install ioredis ---------------------------------------- TITLE: Performing Weighted Set Intersection with ZINTER in Redis using Python DESCRIPTION: This snippet demonstrates using ZINTER with weights. It intersects two sets, applies different weights to each set, includes scores in the result, and uses the SUM aggregation function. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zinter(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ---------------------------------------- TITLE: Executing Redis PING Command in TypeScript DESCRIPTION: Demonstrates how to send a PING command to a Redis server and handle the response. The server will respond with 'PONG' if it is alive and functioning properly. LANGUAGE: typescript CODE: const response = await redis.ping(); console.log(response); // "PONG" ---------------------------------------- TITLE: Removing Set Members with Redis SREM in Python DESCRIPTION: Demonstrates using the SREM command to remove members from a Redis set. First adds three members to a set using SADD, then attempts to remove two members (one existing, one non-existing) using SREM. Returns the count of successfully removed members. LANGUAGE: python CODE: redis.sadd("myset", "one", "two", "three") assert redis.srem("myset", "one", "four") == 1 ---------------------------------------- TITLE: Implementing Delayed Rate Limiting with 'blockUntilReady' in TypeScript DESCRIPTION: The 'blockUntilReady' method allows for delayed processing of requests that exceed the rate limit. It waits until the next window starts before retrying, with a configurable timeout. LANGUAGE: typescript CODE: ratelimit.blockUntilReady( identifier: string, timeout: number ): Promise LANGUAGE: typescript CODE: // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, }); // `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds const { success } = await ratelimit.blockUntilReady("id", 30_000); if (!success) { return "Unable to process, even after 30 seconds"; } doExpensiveCalculation(); return "Here you go!"; ---------------------------------------- TITLE: Retrieving Elements from a Redis Sorted Set with ZRANGE DESCRIPTION: Basic example of using ZRANGE to retrieve elements from a Redis sorted set. First adds two members with their scores to a sorted set, then retrieves elements within a specific range. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, ) const res = await redis.zrange("key", 1, 3) console.log(res) // ["m2"] ---------------------------------------- TITLE: Adding Basic Entry to Redis Stream DESCRIPTION: Demonstrates adding a simple entry to a Redis stream with automatic ID generation. Creates a new entry with name and age fields. LANGUAGE: python CODE: redis.xadd(key, "*", { name: "John Doe", age: 30 }) ---------------------------------------- TITLE: Setting JSON Value with NX Option in Redis DESCRIPTION: This example shows how to set a JSON value at a path only if it doesn't already exist (NX option). It uses the json.set method with an additional options object specifying nx:true. LANGUAGE: typescript CODE: const value = ... redis.json.set(key, "$.path", value, { nx:true }); ---------------------------------------- TITLE: Incrementing Float Value in Redis using TypeScript DESCRIPTION: Demonstrates how to increment a float value stored at a specific key in Redis. First sets an initial value using set() command, then increments it by a float value using incrbyfloat() command. LANGUAGE: typescript CODE: await redis.set("key", 6); await redis.incrbyfloat("key", 4,5); // returns 10.5 ---------------------------------------- TITLE: Retrieving the Leaderboard with Latency Measurement using cURL DESCRIPTION: Shell command using cURL to retrieve the leaderboard data from the Cloudflare Workers API with additional output to measure and display the request latency. LANGUAGE: shell CODE: curl -w '\n Latency: %{time_total}s\n' http://127.0.0.1:8787 ---------------------------------------- TITLE: Implementing Redis Monitor with ioredis in TypeScript DESCRIPTION: This code snippet demonstrates how to set up a monitor for an Upstash Redis instance using ioredis. It establishes a monitor connection and configures an event handler to log all executed commands to the console, including timestamps, arguments, source, and database information. LANGUAGE: ts CODE: const monitor = await redis.monitor() monitor.on("monitor", (time, args, source, database) => { console.log(time, args, source, database) }) ---------------------------------------- TITLE: Checking Script Existence in Redis Cache using Python DESCRIPTION: Demonstrates how to check if multiple scripts exist in Redis script cache using their SHA1 hashes. The response is a list of boolean values where 1 indicates the script exists and 0 indicates it doesn't exist. LANGUAGE: python CODE: # Script 1 exists # Script 0 does not await redis.scriptExists("", "") == [1, 0] ---------------------------------------- TITLE: Redis Script Flush with Async Option - TypeScript DESCRIPTION: Example showing how to use scriptFlush with the async option enabled for asynchronous script cache clearing. LANGUAGE: typescript CODE: await redis.scriptFlush({ async: true, }); ---------------------------------------- TITLE: Setting List Element Using LSET in Redis with TypeScript DESCRIPTION: Demonstrates how to modify a list element at a specific index using LSET command. First pushes elements to create a list, then uses LSET to replace the element at index 1. The resulting list will have the new element 'd' replacing 'b' at index 1. LANGUAGE: typescript CODE: await redis.lpush("key", "a", "b", "c"); await redis.lset("key", 1, "d"); // list is now ["a", "d", "c"] ---------------------------------------- TITLE: Clearing JSON Values in Redis Using JSON.CLEAR DESCRIPTION: Basic example of using JSON.CLEAR to clear all values at the root level of a JSON document stored in Redis. Returns the number of cleared keys. LANGUAGE: python CODE: redis.json.clear("key") ---------------------------------------- TITLE: Creating a Java Serverless Project DESCRIPTION: Command to create a new serverless project using the AWS Java Maven template. The project is named 'counter-api' and created in a directory called 'aws-java-counter-api'. LANGUAGE: shell CODE: serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api ---------------------------------------- TITLE: Installing Celery with Redis Support DESCRIPTION: Command to install Celery with Redis support using pip. This installs the Celery package along with its Redis dependencies. LANGUAGE: bash CODE: pip install "celery[redis]" ---------------------------------------- TITLE: Initializing Upstash Redis Client in JavaScript DESCRIPTION: This snippet demonstrates how to initialize an Upstash Redis client using the @upstash/redis package. It requires the Upstash Redis REST URL and token as environment variables. LANGUAGE: javascript CODE: import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "", token: "", }); const data = await redis.set("foo", "bar"); ---------------------------------------- TITLE: Incrementing Score in Redis Sorted Set (TypeScript) DESCRIPTION: This snippet demonstrates using the 'incr' option with ZADD to increment the score of a member in a Redis sorted set. It behaves like the ZINCRBY command and can only be used with one score-element pair. LANGUAGE: typescript CODE: await redis.zadd( "key", { cincrh: true }, { score: 2, member: "member" }, ) ---------------------------------------- TITLE: Redis BITPOS Basic Usage Example in Python DESCRIPTION: Demonstrates setting bits using setbit and then finding their positions using bitpos. Shows both finding set (1) and clear (0) bits, including basic position checks and assertions. LANGUAGE: python CODE: redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) assert redis.bitpos("mykey", 1) == 7 assert redis.bitpos("mykey", 0) == 0 # With a range assert redis.bitpos("mykey", 1, 0, 2) == 0 assert redis.bitpos("mykey", 1, 2, 3) == -1 ---------------------------------------- TITLE: Enabling Analytics for Rate Limiting in JavaScript DESCRIPTION: This snippet demonstrates how to enable analytics for rate limiting, which collects data on rate limit successes and failures. The collected information can be viewed in the Upstash console. LANGUAGE: javascript CODE: const ratelimit = new Ratelimit({ redis, analytics: true, limiter: Ratelimit.slidingWindow(60, "10s"), }); ---------------------------------------- TITLE: Implementing Fixed Window Rate Limiting with Redis - Regional DESCRIPTION: Creates a rate limiter that allows 10 requests per 10 seconds using the fixed window algorithm with regional Redis setup. LANGUAGE: typescript CODE: const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.fixedWindow(10, "10 s"), }); ---------------------------------------- TITLE: Setting Key Expiration with PEXPIREAT in TypeScript DESCRIPTION: This snippet demonstrates how to use the PEXPIREAT command to set an expiration time on a key. It calculates a timestamp 10 minutes in the future and applies it to the key. LANGUAGE: typescript CODE: const 10MinutesFromNow = Date.now() + 10 * 60 * 1000; await redis.pexpireat(key, 10MinutesFromNow); ---------------------------------------- TITLE: Removing Members by Score Range from Redis Sorted Set in TypeScript DESCRIPTION: This example demonstrates how to use the ZREMRANGEBYSCORE command to remove members from a Redis sorted set based on a score range. It removes all members with scores between 2 and 5 (inclusive) from the sorted set with the key 'key'. LANGUAGE: typescript CODE: await redis.zremrangebyscore("key", 2, 5) ---------------------------------------- TITLE: Sliding Window Rate Limit Calculation Example DESCRIPTION: Demonstrates the calculation logic for sliding window rate limiting algorithm with a 60-second window. LANGUAGE: typescript CODE: limit = 10 // 4 request from the old window, weighted + requests in current window rate = 4 * ((60 - 15) / 60) + 5 = 8 return rate < limit // True means we should allow the request ---------------------------------------- TITLE: Installing Upstash Ratelimit Strapi Plugin with Yarn DESCRIPTION: Command to install the Upstash Ratelimit Strapi plugin using Yarn package manager. LANGUAGE: bash CODE: yarn add @upstash/strapi-plugin-upstash-ratelimit ---------------------------------------- TITLE: Querying TTL for Redis Key in TypeScript DESCRIPTION: Retrieves the remaining time to live (in seconds) for a given Redis key. Returns a negative value if the key doesn't exist or has no expiration set. The operation is asynchronous and returns a Promise resolving to an integer. LANGUAGE: typescript CODE: const seconds = await redis.ttl(key); ---------------------------------------- TITLE: Counting Elements in a Redis Sorted Set with ZCARD Command in TypeScript DESCRIPTION: This example demonstrates how to add members to a sorted set using zadd and then count the elements using zrank (though the example appears to use zrank instead of zcard). The code adds two members with different scores to a sorted set and then retrieves the count of elements. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zrank("key"); console.log(elements); // 2 ---------------------------------------- TITLE: Redis Set Intersection Example in Python DESCRIPTION: Demonstrates how to use the SINTER command to find common elements between two sets. The example creates two sets with some overlapping elements, performs the intersection, and verifies the result count. LANGUAGE: python CODE: redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sinter("destination", "set1", "set2") == 1 ---------------------------------------- TITLE: Calculating Sliding Window Ratelimit Approximation DESCRIPTION: Demonstrates the calculation used in the Sliding Window algorithm to determine if a request should be allowed. This example shows how requests from the previous window are weighted based on time proximity. LANGUAGE: python CODE: limit = 10 # 4 request from the old window, weighted + requests in current window rate = 4 * ((60 - 15) / 60) + 5 = 8 return rate < limit # True means we should allow the request ---------------------------------------- TITLE: Implementing Multiple Rate Limits for Different User Types in TypeScript DESCRIPTION: This code shows how to apply different rate limits to different user types, such as free and paid users. It creates separate Ratelimit instances with different configurations for each user type. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; import { Ratelimit } from "@upstash/ratelimit"; const redis = Redis.fromEnv(); const ratelimit = { free: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:free", limiter: Ratelimit.slidingWindow(10, "10s"), }), paid: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:paid", limiter: Ratelimit.slidingWindow(60, "10s"), }), }; await ratelimit.free.limit(ip); // or for a paid user you might have an email or userId available: await ratelimit.paid.limit(userId); ---------------------------------------- TITLE: Retrieving JSON Value in RESP Format with Python Redis Client DESCRIPTION: Example showing how to use the json.resp() method to retrieve a JSON value at a specific path in RESP format. Takes a key and path parameter, where path defaults to root ($) if not specified. LANGUAGE: python CODE: resp = redis.json.resp("key", "$.path") ---------------------------------------- TITLE: Chaining Redis Pipeline Commands in Python DESCRIPTION: Demonstrates how to chain multiple Redis commands in a pipeline for a more concise syntax when batching operations together. LANGUAGE: python CODE: pipeline = redis.pipeline() pipeline.set("foo", 1).incr("foo").get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ---------------------------------------- TITLE: Creating Todo Model and Related Files DESCRIPTION: Artisan command to generate Todo model with associated files LANGUAGE: shell CODE: php artisan make:model Todo -cfmr --api ---------------------------------------- TITLE: Finding Set Difference using Redis SDIFF Command in Python DESCRIPTION: Demonstrates how to find the difference between two Redis sets using the SDIFF command. The example first adds elements to two sets and then finds elements that are in set1 but not in set2. LANGUAGE: python CODE: redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sdiff("set1", "set2") == {"a", "b"} ---------------------------------------- TITLE: Removing Elements from Redis Sorted Set by Lexicographical Range in Python DESCRIPTION: This code snippet demonstrates how to use the ZREMRANGEBYLEX command in Redis using Python. It removes all members in a sorted set between the given lexicographical range 'alpha' and 'omega'. LANGUAGE: python CODE: redis.zremrangebylex("key", "alpha", "omega") ---------------------------------------- TITLE: Using ZREVRANK to Get Reverse Rank of a Member in Redis Sorted Set with Python DESCRIPTION: This example demonstrates how to use the ZREVRANK command in Redis by first adding members to a sorted set with the ZADD command, then retrieving the reverse rank of a specific member. The reverse rank starts from 0 for the member with the highest score. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrevrank("myset", "a") == 2 ---------------------------------------- TITLE: Demonstrating Base64 Encoded Response Issue DESCRIPTION: Example showing how Redis responses are base64 encoded by default, which can cause unexpected output when retrieving stored values. LANGUAGE: ts CODE: await redis.set("key", "value"); const data = await redis.get("key"); console.log(data); // dmFsdWU= ---------------------------------------- TITLE: Using ZRANGE with byScore Option in Redis DESCRIPTION: Example demonstrating how to use ZRANGE with the byScore option to retrieve elements based on their score range rather than their index range. This retrieves all elements with scores between 1 and 2. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, ) const res = await redis.zrange("key", 1, 2, { byScore: true }) console.log(res) // ["m1", "m2"] ---------------------------------------- TITLE: Storing Set Intersection in Redis using TypeScript DESCRIPTION: Demonstrates using SINTERSTORE to find the intersection between two sets and store the result in a destination key. First creates two sets with sadd, then finds their intersection and stores it in a destination key. LANGUAGE: typescript CODE: await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sinterstore("destination", "set1", "set2"); ---------------------------------------- TITLE: Retrieving Single Random Member from Redis Set in Python DESCRIPTION: This snippet demonstrates how to use the SRANDMEMBER command to retrieve a single random member from a Redis set. It first adds members to the set using SADD, then retrieves a random member and asserts it's one of the added values. LANGUAGE: python CODE: redis.sadd("myset", "one", "two", "three") assert redis.srandmember("myset") in {"one", "two", "three"} ---------------------------------------- TITLE: Redis Error Message for Daily Request Limit DESCRIPTION: Example of the error message returned when a database exceeds its maximum daily request count limit on Upstash Redis. LANGUAGE: text CODE: ReplyError: ERR max daily request limit exceeded ---------------------------------------- TITLE: Using JSON.GET with Formatting Options in Redis DESCRIPTION: Example of using JSON.GET with additional formatting options to control the appearance of the returned JSON. Options include indent (for nested levels), newline (end of line character), and space (between key and value). LANGUAGE: typescript CODE: const value = await redis.json.get("key", { indent: " ", newline: "\n", space: " ", }, "$.path.to.somewhere"); ---------------------------------------- TITLE: Renaming Redis Keys Using Python Client DESCRIPTION: Example showing how to rename keys in Redis using the Python client. The snippet demonstrates setting a key, renaming it, and handling errors when trying to rename nonexistent keys. LANGUAGE: python CODE: redis.set("key1", "Hello") redis.rename("key1", "key2") assert redis.get("key1") is None assert redis.get("key2") == "Hello" # Renaming a nonexistent key throws an exception redis.rename("nonexistent", "key3") ---------------------------------------- TITLE: Defining RatelimitResponse Type in TypeScript DESCRIPTION: This type definition outlines the structure of the response returned by the 'limit' method. It includes information such as success status, limit details, remaining requests, reset time, and additional metadata. LANGUAGE: typescript CODE: export type RatelimitResponse = { /** * Whether the request may pass(true) or exceeded the limit(false) */ success: boolean; /** * Maximum number of requests allowed within a window. */ limit: number; /** * How many requests the user has left within the current window. */ remaining: number; /** * Unix timestamp in milliseconds when the limits are reset. */ reset: number; /** * For the MultiRegion setup we do some synchronizing in the background, after returning the current limit. * Or when analytics is enabled, we send the analytics asynchronously after returning the limit. * In most case you can simply ignore this. * * On Vercel Edge or Cloudflare workers, you need to explicitly handle the pending Promise like this: * * ```ts * const { pending } = await ratelimit.limit("id") * context.waitUntil(pending) * ``` * * See `waitUntil` documentation in * [Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/#contextwaituntil) * and [Vercel](https://vercel.com/docs/functions/edge-middleware/middleware-api#waituntil) * for more details. * ``` */ pending: Promise; /** * Reason behind the result in `success` field. * - Is set to "timeout" when request times out * - Is set to "cacheBlock" when an identifier is blocked through cache without calling redis because it was * rate limited previously. * - Is set to "denyList" when identifier or one of ip/user-agent/country parameters is in deny list. To enable * deny list, see `enableProtection` parameter. To edit the deny list, see the Upstash Ratelimit Dashboard * at https://console.upstash.com/ratelimit. * - Is set to undefined if rate limit check had to use Redis. This happens in cases when `success` field in * the response is true. It can also happen the first time sucecss is false. */ reason?: RatelimitResponseType; /** * The value which was in the deny list if reason: "denyList" */ deniedValue?: string; }; ---------------------------------------- TITLE: Executing GETSET Command in TypeScript with Redis DESCRIPTION: Demonstrates how to use the GETSET command to atomically retrieve and update a key's value. The command returns the old value stored at the key before setting the new value, or null if the key didn't exist. LANGUAGE: typescript CODE: const oldValue = await redis.getset("key", newValue); ---------------------------------------- TITLE: Retrieving Multiple JSON Values with JSON.MGET in TypeScript DESCRIPTION: Demonstrates how to use the JSON.MGET command to fetch values from the same path across multiple JSON documents. The command accepts an array of keys and a JSON path expression to specify which values to retrieve. LANGUAGE: typescript CODE: const values = await redis.json.mget(["key1", "key2"], "$.path.to.somewhere"); ---------------------------------------- TITLE: Todo Controller with Cache Implementation DESCRIPTION: Controller implementing CRUD operations with Redis caching LANGUAGE: php CODE: validate([ 'title' => 'required|string|max:255', ]); $todo = Todo::create($request->all()); Cache::forget(self::CACHE_KEY); return response()->json($todo, Response::HTTP_CREATED); } public function show(Todo $todo): Todo { return Cache::flexible( "todo.{$todo->id}", self::CACHE_TTL, function () use ($todo) { return $todo; } ); } public function update(Request $request, Todo $todo): JsonResponse { $request->validate([ 'title' => 'required|string|max:255', ]); $todo->update($request->all()); Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json($todo); } public function destroy(Todo $todo): JsonResponse { $todo->delete(); Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json(null, Response::HTTP_NO_CONTENT); } } ---------------------------------------- TITLE: Redis ZUNIONSTORE with Aggregation in Python DESCRIPTION: Example showing how to use zunionstore with score aggregation. Uses the SUM aggregation method and returns scores with elements. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ---------------------------------------- TITLE: Incrementing Hash Field Value Using HINCRBY in Python DESCRIPTION: This snippet demonstrates how to use the HINCRBY command in Python to increment a hash field value. It first sets a field value using HSET, then increments it by 10 using HINCRBY, and finally asserts that the new value is 15. LANGUAGE: python CODE: redis.hset("myhash", "field1", 5) assert redis.hincrby("myhash", "field1", 10) == 15 ---------------------------------------- TITLE: Retrieving Remaining Tokens with 'getRemaining' in TypeScript DESCRIPTION: The 'getRemaining' method returns the number of remaining tokens/requests available for a specific identifier, along with the reset timestamp. It returns a Promise with the remaining count and reset time. LANGUAGE: typescript CODE: ratelimit.getRemaining(identifier: string): Promise<{ remaining: number; reset: number; }> ---------------------------------------- TITLE: Retrieving JSON Array Length in Redis using Python DESCRIPTION: Demonstrates how to get the length of a JSON array stored in Redis using the json.arrlen() method. The command takes a key and path parameter to specify which array's length to return. LANGUAGE: python CODE: length = redis.json.arrlen("key", "$.path.to.array") ---------------------------------------- TITLE: Trimming JSON Array in Redis using TypeScript DESCRIPTION: This snippet demonstrates how to use the JSON.ARRTRIM command in Redis to trim an array within a JSON structure. It specifies the key, path to the array, and the start and stop indices for trimming. LANGUAGE: typescript CODE: const length = await redis.json.arrtrim("key", "$.path.to.array", 2, 10); ---------------------------------------- TITLE: Toggling Boolean Value in Redis JSON Using TypeScript DESCRIPTION: Demonstrates how to toggle a boolean value stored at a specific path within a Redis JSON entry. The command returns the new boolean value after toggling. LANGUAGE: typescript CODE: const bool = await redis.json.toggle("key", "$.path.to.bool"); ---------------------------------------- TITLE: Performing Bitwise AND Operation in Redis using TypeScript DESCRIPTION: Demonstrates how to use the BITOP command to perform a bitwise AND operation between two source keys and store the result in a destination key. The command returns the size of the resulting string stored in the destination key. LANGUAGE: typescript CODE: await redis.bitop("AND", "destKey", "sourceKey1", "sourceKey2"); ---------------------------------------- TITLE: Using ZINTERSTORE with Aggregation in Redis (Python) DESCRIPTION: This example shows how to use ZINTERSTORE with the 'SUM' aggregation function and the 'withscores' option. It calculates the intersection of two sets, summing the scores of matching elements. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zinterstore("dest", ["key1", "key2"], withscores=True, aggregate="SUM") assert result == 3 ---------------------------------------- TITLE: Resetting Used Tokens with 'resetUsedTokens' in TypeScript DESCRIPTION: The 'resetUsedTokens' method resets the state of the rate limiting algorithm for a specific identifier. It returns a Promise that resolves when the operation is complete. LANGUAGE: typescript CODE: ratelimit.resetUsedTokens(identifier: string): Promise ---------------------------------------- TITLE: Deploying to Google Cloud Run DESCRIPTION: Command to deploy the containerized application to Google Cloud Run with public access, specifying the container image, platform, region, and authentication settings. LANGUAGE: bash CODE: gcloud run deploy cloud-run-sessions \ --image gcr.io/cloud-run-sessions/main:v0.1 \ --platform managed \ --region us-central1 \ --allow-unauthenticated ---------------------------------------- TITLE: Using ZRANGE with Reverse Ordering in Redis with Python DESCRIPTION: Shows how to use the zrange command with the rev parameter to return elements in reverse order. The example adds elements to a sorted set and then retrieves them in reverse order. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, rev=True) == ["c", "b"] ---------------------------------------- TITLE: Trimming a Redis List with LTRIM in Python DESCRIPTION: This snippet demonstrates how to use the LTRIM command to trim a Redis list. It first pushes elements to a list, then trims it to keep only the first two elements, and finally verifies the result. LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.ltrim("mylist", 0, 1) == True assert redis.lrange("mylist", 0, -1) == ["one", "two"] ---------------------------------------- TITLE: Executing FLUSHDB Command in Redis using TypeScript DESCRIPTION: Demonstrates how to use the FLUSHDB command in Redis to delete all keys in the current database. It shows both synchronous and asynchronous implementations. The async option determines whether the operation is performed asynchronously, defaulting to synchronous if not specified. LANGUAGE: typescript CODE: await redis.flushdb(); LANGUAGE: typescript CODE: await redis.flushdb({async: true}) ---------------------------------------- TITLE: Retrieving Hash Field Values with HGET in Python DESCRIPTION: Demonstrates retrieving values from a hash using the HGET command in Redis. The example shows setting a hash value with HSET and then retrieving it with HGET, including handling of missing fields which return None. LANGUAGE: python CODE: redis.hset("myhash", "field1", "Hello") assert redis.hget("myhash", "field1") == "Hello" assert redis.hget("myhash", "field2") is None ---------------------------------------- TITLE: Querying Sorted Set Count with Score Range in TypeScript DESCRIPTION: Demonstrates how to use the ZCOUNT command to count elements in a Redis sorted set within a specified score range. The example shows adding elements to a sorted set and then counting elements with scores between an exclusive minimum of 1 and positive infinity. LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zcount("key", "(1", "+inf"); console.log(elements); // 1 ---------------------------------------- TITLE: getRemaining() Commands Table DESCRIPTION: Shows Redis command costs for getRemaining() method across different algorithms LANGUAGE: markdown CODE: | Algorithm | Command Count | Commands | | -------------- | ------------- | -------------- | | Fixed Window | 2 | EVAL, GET | | Sliding Window | 3 | EVAL, GET, GET | | Token Bucket | 2 | EVAL, HMGET | ---------------------------------------- TITLE: Removing Highest Scored Members from Redis Sorted Set using ZPOPMAX DESCRIPTION: This snippet demonstrates how to use the ZPOPMAX command to remove and return up to 4 members with the highest scores from a sorted set in Redis. The 'key' parameter specifies the sorted set, and '4' indicates the maximum number of members to remove. LANGUAGE: typescript CODE: const popped = await redis.zpopmax("key", 4); ---------------------------------------- TITLE: Retrieving Substring from Redis Key using GETRANGE in TypeScript DESCRIPTION: This snippet demonstrates how to use the GETRANGE command in Redis to retrieve a substring of a value stored at a specific key. It takes the key name and start and end indices as arguments. LANGUAGE: typescript CODE: const substring = await redis.getrange("key", 2, 4); ---------------------------------------- TITLE: Setting JSON Value at Path in Redis DESCRIPTION: This snippet demonstrates how to set a JSON value at a specific path within a key using Redis. It uses the json.set method, which takes the key, path, and value as arguments. LANGUAGE: typescript CODE: redis.json.set(key, "$.path", value); ---------------------------------------- TITLE: Setting JSON Value at Path in Redis DESCRIPTION: This snippet demonstrates how to set a JSON value at a specific path within a key using Redis. It uses the json.set method, which takes the key, path, and value as arguments. LANGUAGE: typescript CODE: redis.json.set(key, "$.path", value); ---------------------------------------- TITLE: Removing Multiple Random Members from a Redis Set Using SPOP DESCRIPTION: This example shows how to remove multiple random members from a set by specifying the count parameter. It adds three members to a set, then removes and returns two random members. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const popped = await redis.spop("set", 2); console.log(popped); // ["a", "b"] ---------------------------------------- TITLE: resetUsedTokens() Commands Table DESCRIPTION: Shows Redis command costs for resetUsedTokens() method across different algorithms LANGUAGE: markdown CODE: | Algorithm | Command Count | Commands | | -------------- | ------------- | -------------------- | | Fixed Window | 3 | EVAL, SCAN, DEL | | Sliding Window | 4 | EVAL, SCAN, DEL, DEL | | Token Bucket | 3 | EVAL, SCAN, DEL | ---------------------------------------- TITLE: Testing Producer Function with Serverless Framework DESCRIPTION: This shell command invokes the producer function locally using the Serverless framework CLI, simulating a new employee registration event. LANGUAGE: shell CODE: serverless invoke local -f hello -d "{name:'Bill Gates', email:'bill@upstash.com', position:'Developer', date:'20210620'}" ---------------------------------------- TITLE: Using Redis BITPOS Command in TypeScript DESCRIPTION: Examples showing how to use the BITPOS command in Redis to find the position of a specific bit value in a string key. The first example shows the basic usage, and the second demonstrates using the command with a specific range. LANGUAGE: typescript CODE: await redis.bitpos("key", 1); LANGUAGE: typescript CODE: await redis.bitpos("key", 1, 5, 20); ---------------------------------------- TITLE: Removing Multiple Elements from Redis List using RPOP in Python DESCRIPTION: This example shows how to use the RPOP command with a count parameter to remove and return multiple elements from the end of a Redis list. It pushes elements to the list using RPUSH, then uses RPOP with a count of 2 to remove the last two elements. LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.rpop("mylist", 2) == ["three", "two"] ---------------------------------------- TITLE: Retrieving Single Random Set Member with Redis SRANDMEMBER DESCRIPTION: Example showing how to retrieve a single random member from a Redis set. First adds multiple members to a set using SADD, then retrieves one random member using SRANDMEMBER. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const member = await redis.srandmember("set"); console.log(member); // "a" ---------------------------------------- TITLE: Retrieving All Hash Values with HVALS in Python DESCRIPTION: This example demonstrates how to set multiple fields in a hash using HSET and then retrieve all the values using HVALS. The hash is created with two fields and their corresponding values, then HVALS returns all values as a list. LANGUAGE: python CODE: redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hvals("myhash") == ["Hello", "World"] ---------------------------------------- TITLE: Counting Hash Fields with Redis HLEN in Python DESCRIPTION: Demonstrates checking the number of fields in a Redis hash using HLEN. Shows initial empty hash check, setting multiple fields with HSET, and verifying the updated field count. LANGUAGE: python CODE: assert redis.hlen("myhash") == 0 redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hlen("myhash") == 2 ---------------------------------------- TITLE: Using Auto IP Deny List with Pending Update in TypeScript DESCRIPTION: This code example demonstrates how to use the limit method with the Auto IP Deny List feature, including handling the pending update of the IP list. It shows how to check the rate limit for a specific IP address and wait for any pending updates to complete. LANGUAGE: typescript CODE: const { success, pending } = await ratelimit.limit( content, {ip: "ip-address"} ); await pending; ---------------------------------------- TITLE: Configuring Serverless YAML for Deployment DESCRIPTION: YAML configuration for the Serverless framework to deploy the autocomplete API to AWS Lambda. LANGUAGE: yaml CODE: service: auto-complete-api # add this if you set REDIS_URL in .env useDotenv: true frameworkVersion: "2" provider: name: aws runtime: nodejs14.x lambdaHashingVersion: 20201221 environment: REDIS_URL: REPLACE_YOUR_REDIS_URL functions: query: handler: handler.query events: - httpApi: path: /query method: get cors: true ---------------------------------------- TITLE: Removing Elements from Redis List using LREM Command in TypeScript DESCRIPTION: This example demonstrates how to use the LREM command to remove occurrences of an element from a Redis list. It first pushes elements to a list, then removes specified occurrences of an element, and logs the number of elements removed. LANGUAGE: typescript CODE: await redis.lpush("key", "a", "a", "b", "b", "c"); const removed = await redis.lrem("key", 4, "b"); console.log(removed) // 2 ---------------------------------------- TITLE: Basic List Position Query in Redis using Python DESCRIPTION: Demonstrates basic usage of LPOS to find the index of an element in a Redis list. Pushes elements to a list and then finds the position of element 'b'. LANGUAGE: python CODE: redis.rpush("key", "a", "b", "c"); assert redis.lpos("key", "b") == 1 ---------------------------------------- TITLE: Installing Upstash Rate Limit SDK with npm DESCRIPTION: This snippet shows how to install the Upstash Rate Limit SDK using npm. It's a prerequisite step for using the SDK in your project. LANGUAGE: bash CODE: npm install @upstash/ratelimit ---------------------------------------- TITLE: Creating Dockerfile for Node.js Application DESCRIPTION: Dockerfile configuration for containerizing the Node.js application to run on Google Cloud Run. Includes steps for setting up the environment, installing dependencies, and configuring the startup command. LANGUAGE: dockerfile CODE: # Use the official lightweight Node.js 12 image. # https://hub.docker.com/_/node FROM node:12-slim # Create and change to the app directory. WORKDIR /usr/src/app # Copy application dependency manifests to the container image. # A wildcard is used to ensure both package.json AND package-lock.json are copied. # Copying this separately prevents re-running npm install on every code change. COPY package*.json ./ # Install dependencies. RUN npm install # Copy local code to the container image. COPY . ./ # Run the web service on container startup. CMD [ "npm", "start" ] ---------------------------------------- TITLE: PSETEX Command in Redis (TypeScript) DESCRIPTION: Placeholder for the PSETEX command in Redis. This command is typically used to set the value and expiration in milliseconds of a key. LANGUAGE: typescript CODE: ---------------------------------------- TITLE: Handling Asynchronous Synchronization in Cloudflare Workers or Vercel Edge Functions DESCRIPTION: This snippet demonstrates how to handle asynchronous synchronization between databases in Cloudflare Workers or Vercel Edge functions using the 'waitUntil' method to ensure proper completion of dangling promises. LANGUAGE: typescript CODE: const { pending } = await ratelimit.limit("id"); context.waitUntil(pending); ---------------------------------------- TITLE: Serverless Framework Configuration DESCRIPTION: Serverless Framework configuration defining AWS Lambda function, runtime, environment variables, and HTTP endpoint. LANGUAGE: yaml CODE: service: counter-serverless provider: name: aws runtime: nodejs20.x environment: UPSTASH_REDIS_REST_URL: ${env:UPSTASH_REDIS_REST_URL} UPSTASH_REDIS_REST_TOKEN: ${env:UPSTASH_REDIS_REST_TOKEN} functions: counter: handler: handler.counter events: - httpApi: path: / method: get ---------------------------------------- TITLE: Setting JSON Value with XX Option in Redis DESCRIPTION: This snippet demonstrates setting a JSON value at a path only if it already exists (XX option). It uses the json.set method with an additional options object specifying xx:true. LANGUAGE: typescript CODE: const value = ... redis.json.set(key, "$.path", value, { xx:true }); ---------------------------------------- TITLE: Searching Array Index in Redis JSON using TypeScript DESCRIPTION: This code snippet demonstrates how to use the JSON.ARRINDEX command in Redis to find the index of a value in a JSON array. It uses the 'redis' client to execute the command, specifying the key, path to the array, and the value to search for. LANGUAGE: typescript CODE: const index = await redis.json.arrindex("key", "$.path.to.array", "a"); ---------------------------------------- TITLE: Executing Cached Lua Script with EVALSHA in TypeScript DESCRIPTION: Demonstrates how to execute a cached Lua script using its SHA1 hash with the EVALSHA command. The example shows passing an empty array for keys and a single argument 'hello'. LANGUAGE: typescript CODE: const result = await redis.evalsha("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", [], ["hello"]); console.log(result) // "hello" ---------------------------------------- TITLE: Decrementing a Redis Key Value Using DECRBY in TypeScript DESCRIPTION: This example demonstrates how to use the DECRBY command in Redis using TypeScript. It first sets a key to an initial value of 6, then decrements it by 4, resulting in a final value of 2. LANGUAGE: typescript CODE: await redis.set("key", 6); await redis.decrby("key", 4); // returns 2 ---------------------------------------- TITLE: Redis BITPOS Range Search Example in Python DESCRIPTION: Shows how to use BITPOS with a specific range by providing start and end positions for the search operation. LANGUAGE: python CODE: redis.bitpos("key", 1, 5, 20) ---------------------------------------- TITLE: Implementing Rate Limiting with Upstash Redis DESCRIPTION: This code snippet demonstrates how to initialize and use Ratelimit with Upstash Redis. It creates a rate limiter that allows 10 requests per 10 seconds and checks if a request should be allowed. LANGUAGE: typescript CODE: import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, /** * Optional prefix for the keys used in redis. This is useful if you want to share a redis * instance with other applications and want to avoid key collisions. The default prefix is * "@upstash/ratelimit" */ prefix: "@upstash/ratelimit", }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); if (!success) { return "Unable to process at this time"; } doExpensiveCalculation(); return "Here you go!"; ---------------------------------------- TITLE: Configuring CDK Stack for Lambda Function DESCRIPTION: TypeScript code to set up the CDK stack, including the Lambda function configuration, environment variables, and function URL. LANGUAGE: typescript CODE: import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new nodejs.NodejsFunction(this, 'CounterFunction', { entry: 'api/counter.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_20_X, environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, bundling: { format: nodejs.OutputFormat.ESM, target: "node20", nodeModules: ['@upstash/redis'], }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ---------------------------------------- TITLE: Storing the Difference Between Redis Sets with SDIFFSTORE in Python DESCRIPTION: This example demonstrates how to use the SDIFFSTORE command to compute the difference between two Redis sets and store the result in a new set. It first adds elements to two sets, then computes their difference and stores it in a destination set, and finally verifies the contents of the resulting set. LANGUAGE: python CODE: redis.sadd("key1", "a", "b", "c") redis.sadd("key2", "c", "d", "e") # Store the result in a new set assert redis.sdiffstore("res", "key1", "key2") == 2 assert redis.smembers("set") == {"a", "b"} ---------------------------------------- TITLE: Retrieving Single Random Hash Field with Redis HRANDFIELD DESCRIPTION: Example of setting a hash and retrieving a single random field using the HRANDFIELD command. Returns one random field name from the hash. LANGUAGE: typescript CODE: await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const randomField = await redis.hrandfield("key"); console.log(randomField); // one of "id", "username" or "name" ---------------------------------------- TITLE: ZUNIONSTORE with Weights in TypeScript DESCRIPTION: Shows how to use the ZUNIONSTORE command with custom weights for each input set. This example applies different weights to the scores of members from each set during the union operation. LANGUAGE: typescript CODE: await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { weights: [2, 3] }, ); console.log(res) // 2 ---------------------------------------- TITLE: Inserting Values into Redis JSON Array using Python DESCRIPTION: Demonstrates how to insert multiple values into a JSON array at a specified index using Redis JSON.ARRINSERT command. The method returns the new length of the array after insertion. The values are inserted before the specified index, shifting existing elements to the right. LANGUAGE: python CODE: length = redis.json.arrinsert("key", "$.path.to.array", 2, "a", "b") ---------------------------------------- TITLE: Transaction Response Example with Mixed Results in Upstash Redis REST API DESCRIPTION: Example JSON response from a transaction containing both successful and failed Redis commands. The response shows OK results for SET and SETEX, an error for INCR (value not an int), and a numeric result for ZADD. LANGUAGE: json CODE: [ { "result": "OK" }, { "result": "OK" }, { "error": "ERR value is not an int or out of range" }, { "result": 2 } ] ---------------------------------------- TITLE: Implementing Custom Rate Limiting with Token Consumption in Python DESCRIPTION: Demonstrates how to implement custom rate limiting where different requests can consume different amounts of tokens. Uses a fixed window limiter with custom rate parameter for batch processing scenarios. LANGUAGE: python CODE: from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) # pass rate as 5 to subtract 5 from the number of # allowed requests in the window: identifier = "api" response = ratelimit.limit(identifier, rate=5) ---------------------------------------- TITLE: Configuring Global Rate Limits in Strapi DESCRIPTION: Example configuration for applying rate limits to all routes using fixed-window algorithm with Authorization header-based identification. Sets 10 tokens per 20-second window. LANGUAGE: json CODE: { "strapi-plugin-upstash-ratelimit":{ "enabled":true, "resolve":"./src/plugins/strapi-plugin-upstash-ratelimit", "config":{ "enabled":true, "token":"process.env.UPSTASH_REDIS_REST_TOKEN", "url":"process.env.UPSTASH_REDIS_REST_URL", "strategy":[ { "methods":[ "GET", "POST" ], "path":"*", "identifierSource":"header.Authorization", "limiter":{ "algorithm":"fixed-window", "tokens":10, "window":"20s" } } ], "prefix":"@strapi" } } } ---------------------------------------- TITLE: Deleting Multiple Keys in Redis using Python DESCRIPTION: Example demonstrates setting two key-value pairs and then deleting them using the delete command. The code also verifies the deletion by checking that the keys no longer exist. LANGUAGE: python CODE: redis.set("key1", "Hello") redis.set("key2", "World") redis.delete("key1", "key2") assert redis.get("key1") is None assert redis.get("key2") is None ---------------------------------------- TITLE: Using Redis ECHO Command in TypeScript DESCRIPTION: Demonstrates how to use the ECHO command to send and receive a test message from Redis server. The command sends a string message and returns the exact same message, commonly used for connection testing and debugging. LANGUAGE: typescript CODE: const response = await redis.echo("hello world"); console.log(response); // "hello world" ---------------------------------------- TITLE: Configuring Upstash Redis in Wrangler TOML DESCRIPTION: TOML configuration for Cloudflare Workers, including Upstash Redis REST URL and token. LANGUAGE: toml CODE: # wrangler.toml # existing config [vars] UPSTASH_REDIS_REST_TOKEN = "AX_sASQgODM5ZjExZGEtMmI3Mi00Mjcwk3NDIxMmEwNmNkYjVmOGVmZTk5MzQ=" UPSTASH_REDIS_REST_URL = "https://us1-merry-macaque-31458.upstash.io/" ---------------------------------------- TITLE: Retrieving JSON Values with Redis JSON.GET Command in Python DESCRIPTION: This example demonstrates how to use the JSON.GET command with Redis to retrieve a specific value from a JSON document using a path expression. The method accepts a key and a path parameter to locate the desired value within the JSON structure. LANGUAGE: python CODE: value = redis.json.get("key", "$.path.to.somewhere") ---------------------------------------- TITLE: Executing Redis FLUSHDB Command in Python DESCRIPTION: Demonstrates both synchronous and asynchronous methods to flush all keys from the Redis database. The command accepts an optional flush_type parameter that can be set to 'ASYNC' for asynchronous execution. By default, the operation is performed synchronously. LANGUAGE: python CODE: redis.flushall() LANGUAGE: python CODE: redis.flushall(flush_type="ASYNC") ---------------------------------------- TITLE: Connecting with Jedis in Java DESCRIPTION: Example of connecting to Upstash Redis using the Jedis client library in Java, demonstrating authentication and basic Redis operations. LANGUAGE: java CODE: Jedis jedis = new Jedis("YOUR_ENDPOINT", "YOUR_PORT", true); jedis.auth("YOUR_PASSWORD"); jedis.set("foo", "bar"); String value = jedis.get("foo"); System.out.println(value); ---------------------------------------- TITLE: Using SDIFFSTORE with Redis in TypeScript DESCRIPTION: This example demonstrates how to compute the difference between two sets and store the result in a destination set using Redis. It adds members to two sets, computes their difference, and stores the result in a new set. LANGUAGE: typescript CODE: await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sdiff("dest", "set1", "set2"); console.log(diff); // ["a", "b"] ---------------------------------------- TITLE: ZINTERSTORE with Aggregate Function in Redis DESCRIPTION: Illustrates using ZINTERSTORE with an aggregate function to determine how the resulting scores should be computed when members exist in multiple sets. LANGUAGE: typescript CODE: await redis.zadd("key1", { score: 1, member: "member1" }) await redis.zadd("key2",{ score: 1, member: "member1" },{ score: 2, member: "member2" }) const res = await redis.zinterstore("destination",2,["key1", "key2"],{ aggregate: "sum" }); console.log(res) // 1 ---------------------------------------- TITLE: Removing a Random Member from a Redis Set Using SPOP DESCRIPTION: This example demonstrates removing a single random member from a Redis set. First, it adds three members to a set, then pops one random member using the SPOP command. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const popped = await redis.spop("set"); console.log(popped); // "a" ---------------------------------------- TITLE: Performing Bitwise AND Operation with Redis BITOP Command in Python DESCRIPTION: This example demonstrates the usage of the BITOP command in Redis to perform a bitwise AND operation between two keys. It sets bit values for two keys, performs the AND operation, and checks the result. LANGUAGE: python CODE: # key1 = 00000001 # key2 = 00000010 redis.setbit("key1", 0, 1) redis.setbit("key2", 0, 0) redis.setbit("key2", 1, 1) assert redis.bitop("AND", "dest", "key1", "key2") == 1 # result = 00000000 assert redis.getbit("dest", 0) == 0 assert redis.getbit("dest", 1) == 0 ---------------------------------------- TITLE: Pipeline Response Format with Mixed Results DESCRIPTION: Example of the response format from a pipeline request containing both successful and failed commands. Each command result is represented as a separate JSON object in an array. LANGUAGE: json CODE: [ { "result": "OK" }, { "result": "OK" }, { "error": "ERR value is not an int or out of range" }, { "result": 2 } ] ---------------------------------------- TITLE: Error Response Format for Failed Transactions in Upstash Redis REST API DESCRIPTION: JSON error response format when a transaction is discarded as a whole in Upstash Redis REST API. This occurs for syntax errors, unsupported commands, or exceeding request size or daily limits. LANGUAGE: json CODE: { "error": "ERR ..." } ---------------------------------------- TITLE: Rendering TagFilters Component with Upstash Redis Examples DESCRIPTION: This code snippet uses a custom TagFilters component to display a list of Upstash Redis examples. Each example is represented as a TagFilters.Item with properties like type, tags, and URL. The examples cover various technologies and use cases for Upstash Redis. LANGUAGE: JSX CODE: SvelteKit TODO App with Redis Serverless Redis Caching for Strapi ---------------------------------------- TITLE: Pushing Elements with LPUSHX to Existing List in TypeScript DESCRIPTION: Demonstrates pushing an element to an existing list using LPUSHX command. First creates a list with LPUSH, then uses LPUSHX to add another element, returning the new list length of 4. LANGUAGE: typescript CODE: await redis.lpush("key", "a", "b", "c"); const length = await redis.lpushx("key", "d"); console.log(length); // 4 ---------------------------------------- TITLE: Subscribing to a Redis Channel with Server-Sent Events in Upstash REST API DESCRIPTION: Example of subscribing to a Redis pub/sub channel using Upstash REST API. The request uses Server-Sent Events to receive real-time messages published to the 'chat' channel. LANGUAGE: shell CODE: curl -X POST https://us1-merry-cat-32748.upstash.io/subscribe/chat \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" \ -H "Accept:text/event-stream" ---------------------------------------- TITLE: Next.js Page Implementation DESCRIPTION: Implementation of the home page component that uses Upstash Redis to increment and display a counter LANGUAGE: tsx CODE: import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ---------------------------------------- TITLE: Array-based Key Deletion in Redis using TypeScript DESCRIPTION: Demonstrates how to delete multiple keys using the spread operator with an array of keys. This approach is useful when working with dynamic collections of keys. LANGUAGE: typescript CODE: // in case you have an array of keys const keys = ["key1", "key2"]; await redis.del(...keys) ---------------------------------------- TITLE: Basic Redis Script Flush Usage - TypeScript DESCRIPTION: Basic example of using the scriptFlush method to clear the Redis script cache. LANGUAGE: typescript CODE: await redis.scriptFlush(); ---------------------------------------- TITLE: Running SRH Container with Docker Command DESCRIPTION: Docker command to start an SRH container that connects to a local Redis server. Configures the container to run on port 8080 with environment variables for token and connection string. LANGUAGE: bash CODE: docker run \ -it -d -p 8080:80 --name srh \ -e SRH_MODE=env \ -e SRH_TOKEN=your_token_here \ -e SRH_CONNECTION_STRING="redis://your_server_here:6379" \ hiett/serverless-redis-http:latest ---------------------------------------- TITLE: Creating a Serverless Framework Application for AWS Lambda DESCRIPTION: Command line interaction showing how to create a new Serverless Framework application configured for AWS with Node.js and HTTP API. LANGUAGE: shell CODE: ➜ tutorials > ✗ serverless Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ✔ Select A Template: · AWS / Node.js / HTTP API ✔ Name Your Project: · ratelimit-serverless ✔ Template Downloaded ✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · ratelimit-serverless Your new Service "ratelimit-serverless" is ready. Here are next steps: • Open Service Directory: cd ratelimit-serverless • Install Dependencies: npm install (or use another package manager) • Deploy Your Service: serverless deploy ---------------------------------------- TITLE: Setting a Bit in Redis using SETBIT DESCRIPTION: This snippet demonstrates how to use the SETBIT command in Redis to set a single bit in a string. It sets the bit at offset 4 to 1 and returns the original bit value. LANGUAGE: python CODE: original_bit = redis.setbit(key, 4, 1) ---------------------------------------- TITLE: Setting List Element at Specific Index with Redis LSET in Python DESCRIPTION: This example demonstrates how to use the LSET command to modify an element at a specific index in a Redis list. It shows creating a list with RPUSH, successfully updating an element within range, attempting to update an out-of-range element (which fails), and verifying the list contents using LRANGE. LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three") assert redis.lset("mylist", 1, "Hello") == True assert redis.lrange("mylist", 0, -1) == ["one", "Hello", "three"] assert redis.lset("mylist", 5, "Hello") == False assert redis.lrange("mylist", 0, -1) == ["one", "Hello", "three"] ---------------------------------------- TITLE: Configuring Automatic Deserialization in Upstash Redis Client DESCRIPTION: Demonstrates how to disable the default JSON serialization behavior in the Upstash Redis client using two different initialization methods. The automaticDeserialization flag can be set to false either through the Redis constructor or the fromEnv factory method. LANGUAGE: typescript CODE: const redis = new Redis({ // ... automaticDeserialization: false, }); // or const redis = Redis.fromEnv({ automaticDeserialization: false, }); ---------------------------------------- TITLE: Multiply JSON Number Value in Redis using Python DESCRIPTION: Example showing how to multiply a numeric value stored at a specific path in a Redis JSON document. The command takes a key, path to the numeric value, and a multiplier, returning the new value after multiplication. LANGUAGE: python CODE: newValue = redis.json.nummultby("key", "$.path.to.value", 2) ---------------------------------------- TITLE: Calculating Set Intersection with ZINTERSTORE in Redis using Python DESCRIPTION: This snippet demonstrates the basic usage of ZINTERSTORE to calculate the intersection of two sorted sets in Redis. It adds elements to two sets, performs the intersection, and stores the result in a new key. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zinterstore("dest", ["key1", "key2"]) assert result == 1 ---------------------------------------- TITLE: SRH Setup with Docker Compose DESCRIPTION: Docker Compose configuration that sets up both Redis and SRH services. Creates a containerized environment with Redis running on port 6379 and SRH on port 8079. LANGUAGE: yml CODE: version: "3" services: redis: image: redis ports: - "6379:6379" serverless-redis-http: ports: - "8079:80" image: hiett/serverless-redis-http:latest environment: SRH_MODE: env SRH_TOKEN: example_token SRH_CONNECTION_STRING: "redis://redis:6379" # Using `redis` hostname since they're in the same Docker network. ---------------------------------------- TITLE: Creating New Laravel Application DESCRIPTION: Commands to create and navigate to a new Laravel application directory LANGUAGE: shell CODE: laravel new todo-cache cd todo-cache ---------------------------------------- TITLE: Executing Lua Script with Arguments in Redis using Python DESCRIPTION: This example shows how to pass arguments to a Lua script using the eval_ro method in Redis. The script simply returns the first argument passed to it, demonstrating how to access script arguments. LANGUAGE: python CODE: assert redis.eval_ro("return ARGV[1]", args=["Hello"]) == "Hello" ---------------------------------------- TITLE: Retrieving Multiple Scores from Redis Sorted Set with ZMSCORE in TypeScript DESCRIPTION: This example demonstrates how to use the ZMSCORE command to retrieve the scores of multiple members from a Redis sorted set. First, it creates a sorted set with the ZADD command, adding four members with different scores. Then it uses ZMSCORE to retrieve the scores of specific members ('m2' and 'm4'). LANGUAGE: typescript CODE: await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, { score: 4, member: "m4" }, ) const scores = await redis.zmscore("key", ["m2", "m4"]) console.log(scores) // [2, 4] ---------------------------------------- TITLE: Implementing Counter Function in Python DESCRIPTION: Defines a Python function that increments a counter in Redis and returns the count. It uses the upstash_redis library to interact with Redis. LANGUAGE: python CODE: from upstash_redis import Redis redis = Redis.from_env() def handler(event, context): count = redis.incr('counter') return { 'statusCode': 200, 'body': f'Counter: {count}' } ---------------------------------------- TITLE: Executing Asynchronous Tasks with Celery DESCRIPTION: Python code to execute a Celery task asynchronously and retrieve its result. It demonstrates submitting a task and waiting for its completion. LANGUAGE: python CODE: from tasks import add result = add.delay(4, 6) print(f"Task state: {result.state}") # Outputs 'PENDING' initially # Wait for the result output = result.get(timeout=10) print(f"Task result: {output}") # Outputs '10' ---------------------------------------- TITLE: Redis EVAL with Arguments DESCRIPTION: Shows how to pass and access arguments in a Lua script using ARGV array. The example demonstrates returning the first argument passed to the script. LANGUAGE: python CODE: assert redis.eval("return ARGV[1]", args=["Hello"]) == "Hello" ---------------------------------------- TITLE: Importing Redis with Fetch Polyfill for Node.js v17 and Earlier DESCRIPTION: Shows the alternative import path for Node.js environments that don't have native fetch support (v17 and earlier). This special import includes a fetch polyfill. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis/with-fetch"; ---------------------------------------- TITLE: Defining Router Paths for the Application DESCRIPTION: Router configuration that defines the URL paths for the application, including a status page to check Redis connection and the home page with dynamic parameter handling. LANGUAGE: elixir CODE: scope "/", RedixDemoWeb do pipe_through :browser get "/status", PageController, :status get "/", PageController, :home get "/:text", PageController, :home end ---------------------------------------- TITLE: Appending String Values to JSON Path in Redis using TypeScript DESCRIPTION: Demonstrates how to append a string value 'abc' to an existing JSON path using the json.strappend method. The command takes a key, path, and value parameter and returns the length of the resulting array. LANGUAGE: typescript CODE: await redis.json.strappend("key", "$.path.to.str", "abc"); ---------------------------------------- TITLE: Updating Existing Members in Redis Sorted Set (TypeScript) DESCRIPTION: This example shows how to use the 'xx' option with ZADD to only update existing members in a Redis sorted set. It will not add new members if they don't already exist. LANGUAGE: typescript CODE: await redis.zadd( "key", { xx: true }, { score: 2, member: "member" }, ) ---------------------------------------- TITLE: Retrieving List Elements with Redis LRANGE in TypeScript DESCRIPTION: Example showing how to use the LRANGE command to retrieve elements from a Redis list. First pushes three elements to a list using LPUSH, then retrieves elements from index 1 to 2 using LRANGE. LANGUAGE: typescript CODE: await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ---------------------------------------- TITLE: Querying JSON Array Length in Redis using TypeScript DESCRIPTION: Example showing how to retrieve the length of a JSON array at a specified path within a Redis key. Uses path syntax to access nested array elements and returns the array length as an integer. LANGUAGE: typescript CODE: const length = await redis.json.arrlen("key", "$.path.to.array"); ---------------------------------------- TITLE: Incrementing Hash Field Values with Redis HINCRBY DESCRIPTION: Demonstrates setting an initial hash value with HSET and then incrementing it using HINCRBY. The example shows setting a field value to 20 and then incrementing it by 2 to get 22. LANGUAGE: typescript CODE: await redis.hset("key", { field: 20, }); const after = await redis.hincrby("key", "field", 2); console.log(after); // 22 ---------------------------------------- TITLE: Installing Upstash Redis via yarn DESCRIPTION: This snippet shows how to install the @upstash/redis package using yarn. LANGUAGE: bash CODE: yarn add @upstash/redis ---------------------------------------- TITLE: Setting Environment Variables for Upstash Redis Connection DESCRIPTION: This bash command sets the necessary environment variables for connecting to an Upstash Redis database. These variables are used by the application to authenticate and connect to the Redis instance. LANGUAGE: bash CODE: export UPSTASH_REDIS_REST_URL="" export UPSTASH_REDIS_REST_TOKEN="" ---------------------------------------- TITLE: Setting Key Expiration with EXPIREAT in Python DESCRIPTION: Examples of using the EXPIREAT Redis command to set a key to expire at a specific time. Shows both using a datetime object and a unix timestamp to set the expiration time 5 seconds in the future. LANGUAGE: python CODE: # With a datetime object redis.set("mykey", "Hello") redis.expireat("mykey", datetime.datetime.now() + datetime.timedelta(seconds=5)) # With a unix timestamp redis.set("mykey", "Hello") redis.expireat("mykey", int(time.time()) + 5) ---------------------------------------- TITLE: Retrieving Member Rank from Sorted Set using ZRANK in TypeScript DESCRIPTION: Returns the rank of a specified member in a sorted set. This example shows how to use the rank method to retrieve a member's position in the sorted set identified by the given key. LANGUAGE: ts CODE: const rank = await redis.rank("key", "member"); ---------------------------------------- TITLE: Querying JSON Object Length in Redis using TypeScript DESCRIPTION: Demonstrates how to retrieve the number of keys in a JSON object stored in Redis using the json.objlen command. Takes a key parameter and an optional path parameter (defaults to root '$') and returns an array of integers representing object lengths. LANGUAGE: typescript CODE: const lengths = await redis.json.objlen("key", "$.path"); ---------------------------------------- TITLE: Toggling JSON Boolean Value in Redis using Python DESCRIPTION: This code snippet demonstrates how to use the JSON.TOGGLE command in Redis to toggle a boolean value at a specified path within a JSON structure. It uses the 'redis' library to interact with Redis and returns the new value of the boolean. LANGUAGE: python CODE: bool = redis.json.toggle("key", "$.path.to.bool") ---------------------------------------- TITLE: Using RANDOMKEY Command with Upstash Redis Client in TypeScript DESCRIPTION: Demonstrates how to retrieve a random key from a Redis database using the Upstash Redis client. The command takes no arguments and returns a random key as a string, or null if the database is empty. LANGUAGE: typescript CODE: const key = await redis.randomkey(); ---------------------------------------- TITLE: Installing isomorphic-fetch Polyfill for Node.js DESCRIPTION: Installing the isomorphic-fetch package to provide fetch functionality in Node.js v17 and earlier, which is required for the Upstash Redis client. LANGUAGE: bash CODE: npm i isomorphic-fetch ---------------------------------------- TITLE: Configuring Kafka Client in Vercel Environment DESCRIPTION: Initializes a Kafka client using environment variables and demonstrates message production to a topic using the @upstash/kafka package. LANGUAGE: typescript CODE: import { Kafka } from "@upstash/kafka"; const kafka = new Kafka({ url: process.env.UPSTASH_KAFKA_REST_URL, username: process.env.UPSTASH_KAFKA_REST_USERNAME, password: process.env.UPSTASH_KAFKA_REST_PASSWORD, }); await kafka.producer().produce("my-topic", "my-message"); ---------------------------------------- TITLE: Implementing Multiple Rate Limits for Different User Types in Python DESCRIPTION: Shows how to create different rate limits for different user types (free vs paid users) using a custom class. Implements 10 requests per 10 seconds for free users and 60 requests per 10 seconds for paid users. LANGUAGE: python CODE: from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis class MultiRL: def __init__(self) -> None: redis = Redis.from_env() self.free = Ratelimit( redis=redis, limiter=SlidingWindow(max_requests=10, window=10), prefix="ratelimit:free", ) self.paid = Ratelimit( redis=redis, limiter=SlidingWindow(max_requests=60, window=10), prefix="ratelimit:paid", ) # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = MultiRL() ratelimit.free.limit("userIP") ratelimit.paid.limit("userIP") ---------------------------------------- TITLE: Pushing Elements to an Existing List with RPUSHX in Redis using TypeScript DESCRIPTION: This example demonstrates using the RPUSHX command to append an element to an existing list. It first creates a list with LPUSH, then uses RPUSHX to add a new element, and finally logs the returned length. LANGUAGE: typescript CODE: await redis.lpush("key", "a", "b", "c"); const length = await redis.rpushx("key", "d"); console.log(length); // 4 ---------------------------------------- TITLE: Initializing Redis Client in Cloudflare Workers DESCRIPTION: Shows how to initialize an Upstash Redis client in Cloudflare Workers environment. Supports both direct configuration and loading from environment variables in both service worker and module worker formats. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis/cloudflare" const redis = new Redis({ url: , token: , }) // or load directly from global env // service worker const redis = Redis.fromEnv() // module worker export default { async fetch(request: Request, env: Bindings) { const redis = Redis.fromEnv(env) // ... } } ---------------------------------------- TITLE: Using LREM Command in Python Redis Client DESCRIPTION: Demonstrates how to use the LREM command to remove elements from a Redis list. First pushes multiple elements to a list, then removes two occurrences of 'two', and verifies the remaining elements with LRANGE. LANGUAGE: python CODE: redis.rpush("mylist", "one", "two", "three", "two", "one") assert redis.lrem("mylist", 2, "two") == 2 assert redis.lrange("mylist", 0, -1) == ["one", "three", "one"] ---------------------------------------- TITLE: Basic ZRANGE Usage in Redis with Python DESCRIPTION: Demonstrates using the zrange command to retrieve a range of elements from a sorted set. First adds elements to the sorted set with their scores, then retrieves elements at positions 0 and 1. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1) == ["a", "b"] ---------------------------------------- TITLE: Package Name Reference DESCRIPTION: Reference to the upstash-redis package name that is used for Redis operations over HTTP LANGUAGE: plaintext CODE: upstash-redis ---------------------------------------- TITLE: Configuring Apollo Client for GraphQL in Next.js _app.js DESCRIPTION: This code sets up the Apollo Client for GraphQL queries in a Next.js application. It creates an HTTP link with authorization headers and initializes the ApolloClient with the Upstash GraphQL endpoint. LANGUAGE: javascript CODE: import "../styles/globals.css"; import { ApolloClient, ApolloProvider, createHttpLink, InMemoryCache, } from "@apollo/client"; const link = createHttpLink({ uri: "https://graphql-us-east-1.upstash.io/", headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }); const client = new ApolloClient({ uri: "https://graphql-us-east-1.upstash.io/", cache: new InMemoryCache(), link, }); function MyApp({ Component, pageProps }) { return ( {" "} ); } export default MyApp; ---------------------------------------- TITLE: Removing Key Timeout Using Redis PERSIST Command in TypeScript DESCRIPTION: Example showing how to use the persist command to remove a timeout from a Redis key. The command returns 1 if the timeout was successfully removed, or 0 if the key doesn't exist or had no timeout. LANGUAGE: typescript CODE: await redis.persist(key); ---------------------------------------- TITLE: Appending String Values in Redis using TypeScript DESCRIPTION: Demonstrates how to append a string value to an existing key in Redis. The command returns the length of the resulting string after the append operation. LANGUAGE: typescript CODE: await redis.append(key, "Hello"); // returns 5 ---------------------------------------- TITLE: Moving Set Members with Redis SMOVE Command in Python DESCRIPTION: Example demonstrating how to move a member from one Redis set to another using SMOVE command. The code shows adding initial members to source and destination sets, moving a member between them, and verifying the results using smembers command. LANGUAGE: python CODE: redis.sadd("src", "one", "two", "three") redis.sadd("dest", "four") assert redis.smove("src", "dest", "three") == True assert redis.smembers("source") == {"one", "two"} assert redis.smembers("destination") == {"three", "four"} ---------------------------------------- TITLE: Removing Lowest Scored Members from Redis Sorted Set using ZPOPMIN in TypeScript DESCRIPTION: This snippet demonstrates how to use the ZPOPMIN command to remove and return up to 4 members with the lowest scores from a sorted set in Redis. The command is executed using an asynchronous Redis client method. LANGUAGE: typescript CODE: const popped = await redis.zpopmin("key", 4); ---------------------------------------- TITLE: Configuring Upstash Redis Client in Typescript DESCRIPTION: This code demonstrates how to import and configure the Upstash Redis client in a Typescript application. It uses environment variables for the URL and token to securely initialize the client. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis" const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }) ---------------------------------------- TITLE: Implementing Counter View with Upstash Redis DESCRIPTION: Create a view that increments a counter in Redis each time the page is visited. This demonstrates basic Redis operations within a Django view. LANGUAGE: python CODE: from django.http import HttpResponse from upstash_redis import Redis redis = Redis.from_env() def index(request): count = redis.incr('counter') return HttpResponse(f'Page visited {count} times.') ---------------------------------------- TITLE: Initializing Redis Client with Explicit Credentials in TypeScript DESCRIPTION: Example showing how to create a Redis client instance by explicitly providing the Upstash REST URL and token, then performing a basic key retrieval operation. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", }); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ---------------------------------------- TITLE: Using RPUSH to Add Elements to a Redis List in TypeScript DESCRIPTION: This example demonstrates how to use the RPUSH command to add elements to the end of a Redis list. It shows first pushing multiple elements at once, then pushing a single additional element, with each operation returning the new length of the list. LANGUAGE: typescript CODE: const length1 = await redis.rpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.rpush("key", "d"); console.log(length2); // 4 ---------------------------------------- TITLE: Incrementing Member Score in Redis Sorted Set with ZINCRBY Command in TypeScript DESCRIPTION: This example demonstrates how to use the ZINCRBY command to increment a member's score in a Redis sorted set. It first adds a member with a score of 1 to a sorted set, then increments that score by 2, resulting in a final score of 3. LANGUAGE: typescript CODE: await redis.zadd("key", 1, "member"); const value = await redis.zincrby("key", 2, "member"); console.log(value); // 3 ---------------------------------------- TITLE: Create Deployment ZIP DESCRIPTION: Command to create a ZIP archive of the project for AWS Lambda deployment LANGUAGE: bash CODE: zip -r app.zip . ---------------------------------------- TITLE: Adding New Members to Redis Sorted Set (TypeScript) DESCRIPTION: This snippet demonstrates using the 'nx' option with ZADD to only add new members to a Redis sorted set. It will not update scores of existing members. LANGUAGE: typescript CODE: await redis.zadd( "key", { nx: true }, { score: 2, member: "member" }, ) ---------------------------------------- TITLE: Sending Complete Redis Command as JSON Array DESCRIPTION: Alternative method to send Redis commands by providing the entire command as a JSON array in the request body. This example shows how to send a SET command with expiration. LANGUAGE: shell CODE: curl -X POST -d '["SET", "foo", "bar", "EX", 100]' https://us1-merry-cat-32748.upstash.io \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ---------------------------------------- TITLE: Exporting Upstash Redis Credentials DESCRIPTION: Set environment variables for Upstash Redis REST URL and token. These are used to authenticate and connect to the Redis database. LANGUAGE: shell CODE: export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Configuring Redis Queue Connection DESCRIPTION: Environment variable setup for using Redis as Laravel's queue driver. LANGUAGE: shell CODE: QUEUE_CONNECTION="redis" ---------------------------------------- TITLE: Setting Multiple Values with MSET in Redis (TypeScript) DESCRIPTION: Shows how to use the MSET command to set multiple key-value pairs at once in Redis. This operation counts as a single command for billing purposes. The example demonstrates setting different data types as values. LANGUAGE: typescript CODE: await redis.mset({ key1: { a: 1 }, key2: "value2", key3: true, }); ---------------------------------------- TITLE: Updating Project Dependencies DESCRIPTION: Required Python packages including Django and upstash-redis client LANGUAGE: txt CODE: Django==4.1.3 upstash-redis ---------------------------------------- TITLE: Using LLEN Command with Redis in Python DESCRIPTION: This snippet demonstrates how to use the LLEN command in Redis using Python. It first pushes elements to a list using RPUSH, then uses LLEN to get the length of the list. LANGUAGE: python CODE: redis.rpush("key", "a", "b", "c") assert redis.llen("key") == 3 ---------------------------------------- TITLE: Implementing Write and Read Requests in Typescript with Upstash Redis DESCRIPTION: This snippet demonstrates how to implement separate write and read request functions using Upstash Redis in Typescript. It shows basic key-value operations without considering cross-client synchronization. LANGUAGE: typescript CODE: export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); return randomKey; }; export const readRequest = async (randomKey: string) => { const redis = Redis.fromEnv(); const value = await redis.get(randomKey); return value; }; ---------------------------------------- TITLE: Implementing Flask Application with Redis Counter DESCRIPTION: Python code implementing a Flask web application that uses Upstash Redis to create a visit counter. The application increments a counter on each page visit and displays the count. LANGUAGE: python CODE: from flask import Flask from upstash_redis import Redis app = Flask(__name__) redis = Redis.from_env() @app.route('/') def index(): count = redis.incr('counter') return f'Page visited {count} times.' if __name__ == '__main__': app.run(debug=True) ---------------------------------------- TITLE: Adding Start Script to package.json DESCRIPTION: JSON snippet to add the start script to package.json for running the Node.js application. LANGUAGE: json CODE: "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } ---------------------------------------- TITLE: Returning Changed Elements Count in Redis Sorted Set (TypeScript) DESCRIPTION: This example shows how to use the 'ch' option with ZADD to return the count of elements that were added or updated in a Redis sorted set. LANGUAGE: typescript CODE: await redis.zadd( "key", { ch: true }, { score: 2, member: "member" }, ) ---------------------------------------- TITLE: Redis LPOS with Rank Parameter in Python DESCRIPTION: Shows how to use LPOS with the rank parameter to find the nth occurrence of an element in a Redis list. Demonstrates finding the second occurrence of 'b'. LANGUAGE: python CODE: redis.rpush("key", "a", "b", "c", "b"); assert redis.lpos("key", "b", rank=2) == 3 ---------------------------------------- TITLE: Pattern Matching with HSCAN in Redis using TypeScript DESCRIPTION: This example shows how to use the match option with HSCAN to filter fields by a glob-style pattern. It creates a hash with three fields, then uses HSCAN with a match pattern of 'user*' to return only fields that start with 'user'. LANGUAGE: typescript CODE: await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const [newCursor, fields] = await redis.hscan("key", 0, { match: "user*" }); console.log(newCursor); // likely `0` since this is a very small hash console.log(fields); // ["username", "chronark"] ---------------------------------------- TITLE: Retrieving String Length from Hash Field in Redis using TypeScript DESCRIPTION: This code snippet demonstrates how to use the HSTRLEN command in Redis to get the length of a string value stored in a hash field. It uses an asynchronous function to retrieve the length. LANGUAGE: typescript CODE: const length = await redis.hstrlen("key", "field") ---------------------------------------- TITLE: Disabling Keyspace Notifications in Upstash Redis DESCRIPTION: These commands show how to disable all keyspace and keyevent notifications by setting the notify-keyspace-events option to an empty string. LANGUAGE: bash CODE: curl -X POST \ -d '["CONFIG", "SET", "notify-keyspace-events", ""]' \ -H "Authorization: Bearer $UPSTASH_REDIS_REST_TOKEN" \ $UPSTASH_REDIS_REST_URL LANGUAGE: bash CODE: redis-cli --tls -u $UPSTASH_REDIS_CLI_URL config set notify-keyspace-events "" ---------------------------------------- TITLE: Setting Upstash Redis Environment Variables DESCRIPTION: Commands to export the required Upstash Redis credentials as environment variables. LANGUAGE: shell CODE: export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Setting Up Environment Variables for Upstash Redis DESCRIPTION: Content of the .env file containing Upstash Redis connection details. LANGUAGE: bash CODE: UPSTASH_REDIS_REST_URL=your_upstash_redis_url UPSTASH_REDIS_REST_TOKEN=your_upstash_redis_token ---------------------------------------- TITLE: Incrementing JSON Number Value in Redis using Python DESCRIPTION: This snippet demonstrates how to use the JSON.NUMINCRBY command in Redis to increment a numeric value stored at a specific path within a JSON object. It takes a key, a path to the value, and an increment amount as arguments. LANGUAGE: python CODE: newValue = redis.json.numincrby("key", "$.path.to.value", 2) ---------------------------------------- TITLE: Using ZDIFFSTORE in Redis with Python DESCRIPTION: This example demonstrates how to use the ZDIFFSTORE command in Redis using Python. It creates two sorted sets, compares them, and stores the difference in a new key. LANGUAGE: python CODE: redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) # a and b assert redis.zdiffstore("dest", ["key1", "key2"]) == 2 ---------------------------------------- TITLE: Implementing Redis-based Greeting Function in Cloudflare Worker DESCRIPTION: This TypeScript code implements a Cloudflare Worker function that uses Upstash Redis to fetch and return location-based greetings. It checks the user's country from the request headers and retrieves the corresponding greeting from Redis. LANGUAGE: typescript CODE: import { Redis } from '@upstash/redis/cloudflare'; type RedisEnv = { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; }; export default { async fetch(request: Request, env: RedisEnv) { const redis = Redis.fromEnv(env); const country = request.headers.get('cf-ipcountry'); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response('Hello!'); }, }; ---------------------------------------- TITLE: Using ZPOPMAX Command in Python DESCRIPTION: This snippet demonstrates how to use the ZPOPMAX command to remove and return the highest-scored member from a Redis sorted set. It first adds members to a sorted set with different scores, then uses zpopmax to retrieve the member with the highest score. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmax("myset") == [("c", 3)] ---------------------------------------- TITLE: SQL Query for MQTT Message Processing DESCRIPTION: SQL rule to process MQTT messages from temp_hum/emqx topic, extracting timestamp, client ID, temperature and humidity data from the payload. LANGUAGE: sql CODE: SELECT timestamp as up_timestamp, clientid as client_id, payload.temp as temp, payload.hum as hum FROM "temp_hum/emqx" ---------------------------------------- TITLE: Implementing Upstash Redis in Cloudflare Worker (TypeScript) DESCRIPTION: TypeScript code for a Cloudflare Worker that uses Upstash Redis. It increments a counter and returns the current count as a JSON response. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis/cloudflare"; export interface Env { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; } export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); }, }; ---------------------------------------- TITLE: Configuring Redis Environment Variables DESCRIPTION: Environment variable configuration for Upstash Redis connection credentials. LANGUAGE: shell CODE: UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Adding Stream Entry with Trimming in Redis XADD DESCRIPTION: Shows how to append a stream entry while implementing trimming logic. Sets a maximum length of 1000 entries using exact comparison, demonstrating stream size management. LANGUAGE: typescript CODE: await redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", }, }); ---------------------------------------- TITLE: Trimming JSON Array Elements in Redis using Python DESCRIPTION: Demonstrates how to trim a JSON array in Redis to keep only elements between specified start and stop indices. The command returns the length of the resulting array after trimming. LANGUAGE: python CODE: length = redis.json.arrtrim("key", "$.path.to.array", 2, 10) ---------------------------------------- TITLE: Executing Redis Commands with Synchronous and Asynchronous Clients in Python DESCRIPTION: Example code showing basic Redis operations (set and get) using both synchronous and asynchronous client implementations. LANGUAGE: python CODE: 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")) ---------------------------------------- TITLE: Touching Multiple Redis Keys in Python DESCRIPTION: Example showing how to update the access time of multiple Redis keys using the TOUCH command. The command accepts one or more key names and returns the number of keys that were successfully touched. LANGUAGE: python CODE: redis.touch("key1", "key2", "key3") ---------------------------------------- TITLE: Redis Cache Configuration DESCRIPTION: Environment variables setup for using Redis as Laravel's cache store. LANGUAGE: shell CODE: CACHE_STORE="redis" REDIS_CACHE_DB="0" ---------------------------------------- TITLE: Implementing Upstash Redis in Cloudflare Worker (JavaScript) DESCRIPTION: JavaScript code for a Cloudflare Worker that uses Upstash Redis. It increments a counter and returns the current count as a JSON response. LANGUAGE: javascript CODE: import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env, ctx) { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); }, }; ---------------------------------------- TITLE: Alternative Redis Environment Variables for Vercel DESCRIPTION: Alternative environment variable configuration when using Vercel & Upstash integration. LANGUAGE: shell CODE: KV_REST_API_URL= KV_REST_API_TOKEN= ---------------------------------------- TITLE: Implementing Block Until Ready Rate Limiting in Python with Upstash Redis DESCRIPTION: Demonstrates how to implement a blocking rate limiter that waits for a specified timeout period before allowing requests to proceed. Creates a rate limiter allowing 10 requests per 10 seconds with a 30-second timeout. LANGUAGE: python CODE: from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=Redis.from_env(), limiter=SlidingWindow(max_requests=10, window=10), ) response = ratelimit.block_until_ready("id", timeout=30) if not response.allowed: print("Unable to process, even after 30 seconds") else: do_expensive_calculation() print("Here you go!") ---------------------------------------- TITLE: Retrieving Object Keys with JSON.OBJKEYS in Redis using Python DESCRIPTION: This snippet demonstrates how to use the JSON.OBJKEYS operation in Redis to retrieve the keys of an object at a specified path. It uses the 'json.objkeys' method of the Redis client, passing the key of the JSON entry and the path to the object. LANGUAGE: python CODE: keys = redis.json.objkeys("key", "$.path") ---------------------------------------- TITLE: Creating Django Project from Vercel Template DESCRIPTION: Commands to create a new Django application using Vercel's template repository LANGUAGE: shell CODE: npx create-next-app vercel-django --example "https://github.com/vercel/examples/tree/main/python/django" cd vercel-django ---------------------------------------- TITLE: Retrieving Random Fields with Values from Redis Hash - Python DESCRIPTION: Demonstrates retrieving random fields along with their values using the withvalues parameter. Returns an object containing the randomly selected field and its corresponding value. LANGUAGE: python CODE: redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash", count=1, withvalues=True) in [ {"field1": "Hello"}, {"field2": "World"} ] ---------------------------------------- TITLE: Configuring Fly.toml for Redis Environment Variable DESCRIPTION: This TOML snippet shows how to add the Redis URL as an environment variable in the Fly.toml configuration file. This allows the application to access the Redis instance when deployed on Fly.io. LANGUAGE: toml CODE: [env] REDIS_URL = "" ---------------------------------------- TITLE: Installing Create Cloudflare CLI DESCRIPTION: Commands to install the create-cloudflare package using npm or yarn. This tool is used to set up a new Cloudflare Workers project. LANGUAGE: shell CODE: npm create cloudflare@latest LANGUAGE: shell CODE: yarn create cloudflare@latest ---------------------------------------- TITLE: Setting Up Redis Environment Variables DESCRIPTION: Shell commands to export Upstash Redis credentials as environment variables for the application to use when connecting to Redis. LANGUAGE: shell CODE: export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Creating a .env File for Upstash Redis Configuration DESCRIPTION: Example of a .env file containing Upstash Redis connection details. This file can be loaded using python-dotenv to configure environment variables. LANGUAGE: text CODE: UPSTASH_REDIS_HOST= UPSTASH_REDIS_PORT= UPSTASH_REDIS_PASSWORD= { const count = await redis.incr("counter"); return { status: 200, body: `Counter: ${count}` }; }; app.http('CounterFunction', { methods: ['GET', 'POST'], authLevel: 'anonymous', handler: CounterFunction }); ---------------------------------------- TITLE: Retrieving Multiple Random Set Members with Redis SRANDMEMBER DESCRIPTION: Example demonstrating how to retrieve multiple random members from a Redis set by specifying a count parameter. Adds members to a set then retrieves 2 random members. LANGUAGE: typescript CODE: await redis.sadd("set", "a", "b", "c"); const members = await redis.srandmember("set", 2); console.log(members); // ["a", "b"] ---------------------------------------- TITLE: Creating Redis Database with Fly CLI DESCRIPTION: This snippet demonstrates how to create a Redis database using the Fly CLI. It shows the interactive prompts for configuring the database, including organization selection, naming, region selection, and plan choice. LANGUAGE: shell CODE: > flyctl redis create ? Select Organization: upstash (upstash) ? Choose a Redis database name (leave blank to generate one): ? Choose a primary region (can't be changed later) San Jose, California (US) (sjc) Upstash Redis can evict objects when memory is full. This is useful when caching in Redis. This setting can be changed later. Learn more at https://fly.io/docs/reference/redis/#memory-limits-and-object-eviction-policies ? Would you like to enable eviction? No ? Optionally, choose one or more replica regions (can be changed later): ? Select an Upstash Redis plan 3G: 3 GB Max Data Size Your Upstash Redis database silent-tree-6201 is ready. Apps in the upstash org can connect to at redis://default:978ba2e07tyrt67598acd8ac916a@fly-silent-tree-6201.upstash.io If you have redis-cli installed, use fly redis connect to connect to your database. ---------------------------------------- TITLE: Node.js Express Application with Redis Integration DESCRIPTION: This code snippet shows a basic Express.js application that integrates with Redis. It creates a simple server that increments a counter in Redis and returns the visitor number. The Redis client is initialized with a URL from an environment variable. LANGUAGE: javascript CODE: const express = require("express"); const redis = require("redis"); const { promisify } = require("util"); const app = express(); const client = redis.createClient(process.env.REDIS_URL); const getAsync = promisify(client.get).bind(client); const setAsync = promisify(client.set).bind(client); app.get("/", async (req, res) => { const value = await getAsync("counter"); await setAsync("counter", parseInt(value || 0) + 1); res.send(`Hello, visitor number ${value || 0}!`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); ---------------------------------------- TITLE: Setting Up Environment Variables for Redis DESCRIPTION: Environment variable configuration for Upstash Redis connection credentials LANGUAGE: bash CODE: UPSTASH_REDIS_REST_URL=your_upstash_redis_url UPSTASH_REDIS_REST_TOKEN=your_upstash_redis_token ---------------------------------------- TITLE: Setting Timeout for Rate Limiting Requests in TypeScript DESCRIPTION: This code shows how to set a timeout for rate limiting requests, allowing them to pass after a specified duration regardless of the current limit. This can help prevent request rejection due to network issues. LANGUAGE: typescript CODE: const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), timeout: 1000, // 1 second analytics: true, }); ---------------------------------------- TITLE: Flushing Redis Script Cache in Python DESCRIPTION: This snippet demonstrates how to use the script_flush method to remove all scripts from the Redis script cache. The flush_type argument is set to 'ASYNC' for asynchronous flushing. LANGUAGE: python CODE: redis.script_flush(flush_type="ASYNC") ---------------------------------------- TITLE: Deploying AWS CDK Stack DESCRIPTION: Shell commands to synthesize, bootstrap, and deploy the AWS CDK stack to AWS. LANGUAGE: shell CODE: cdk synth cdk bootstrap cdk deploy ---------------------------------------- TITLE: Importing @upstash/redis in TypeScript DESCRIPTION: This snippet shows how to import the @upstash/redis package in a TypeScript project. It's the first step in using the Upstash Redis client in your application. LANGUAGE: typescript CODE: `@upstash/redis` ---------------------------------------- TITLE: Implementing Redis Counter in Next.js Home Page DESCRIPTION: This code snippet shows how to create a home page component in Next.js that uses Upstash Redis to implement a counter. It demonstrates server-side props, Redis initialization, and basic component rendering. LANGUAGE: tsx CODE: import type { InferGetServerSidePropsType, GetServerSideProps } from 'next' import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export const getServerSideProps = (async () => { const count = await redis.incr("counter"); return { props: { count } } }) satisfies GetServerSideProps<{ count: number }> export default function Home({ count, }: InferGetServerSidePropsType) { return (

Counter: {count}

) } ---------------------------------------- TITLE: Establishing Redis Tunnel for Local Development DESCRIPTION: This shell command creates a secure tunnel between the local machine and the Redis instance on Fly.io, allowing for local development and testing access to the remote Redis database. LANGUAGE: shell CODE: fly redis connect ---------------------------------------- TITLE: Setting Environment Variables for Local Next.js Project DESCRIPTION: This code snippet shows the content to be added to the .env.local file for a local Next.js project to set the required environment variables. LANGUAGE: plaintext CODE: UPSTASH_REDIS_REST_URL=**** UPSTASH_REDIS_REST_TOKEN=**** ---------------------------------------- TITLE: Installing upstash-ratelimit library using pip DESCRIPTION: This command installs the upstash-ratelimit library using pip, the Python package installer. LANGUAGE: bash CODE: pip install upstash-ratelimit ---------------------------------------- TITLE: Performing SUNION Operation Between Redis Sets in Python DESCRIPTION: This example demonstrates how to use the SUNION command to get the union of two Redis sets. It first adds elements to two different sets using SADD, then uses SUNION to retrieve the combined unique elements from both sets. LANGUAGE: python CODE: redis.sadd("key1", "a", "b", "c") redis.sadd("key2", "c", "d", "e") assert redis.sunion("key1", "key2") == {"a", "b", "c", "d", "e"} ---------------------------------------- TITLE: AWS Lambda Redis Integration Function DESCRIPTION: JavaScript code for AWS Lambda function that connects to Upstash Redis and performs basic set/get operations LANGUAGE: javascript CODE: var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.handler = async (event) => { await client.set("foo", "bar"); let result = await client.get("foo"); let response = { statusCode: 200, body: JSON.stringify({ result: result, }), }; return response; }; ---------------------------------------- TITLE: Adding and Counting Members in Redis Sorted Set using Python DESCRIPTION: Example demonstrates adding multiple members to a sorted set with scores and verifying the count using zlexcount. The code adds three members 'a', 'b', and 'c' with scores 1, 2, and 3 respectively, then checks the total count between lexicographical ranges '-' and '+'. LANGUAGE: python CODE: redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zlexcount("myset", "-", "+") == 3 ---------------------------------------- TITLE: Deploying Application After Configuration DESCRIPTION: Command to deploy the application to Fly.io after configuration has been completed, making the website available. LANGUAGE: bash CODE: fly deploy ---------------------------------------- TITLE: Parsing Redis URL in Application Start Function DESCRIPTION: Extracts connection parameters (password, host, port) from the REDIS_URL environment variable using regex to prepare for Redis connection. LANGUAGE: elixir CODE: def start(_type, _args) do [_, password, host, port] = Regex.run( ~r{(.+):(.+)@(.+):(\d+)}, System.get_env("REDIS_URL"), capture: :all_but_first ) port = elem(Integer.parse(port), 0) # ... end ---------------------------------------- TITLE: Setting Environment Variables for Cloudflare Worker DESCRIPTION: These commands show how to set the required environment variables for a Cloudflare Worker using Wrangler CLI. LANGUAGE: bash CODE: npx wrangler secret put UPSTASH_REDIS_REST_URL npx wrangler secret put UPSTASH_REDIS_REST_TOKEN ---------------------------------------- TITLE: Initializing Node Project and Installing Dependencies DESCRIPTION: Commands to initialize a Node.js project and install required dependencies for the session management application including Express, Redis, and session middleware. LANGUAGE: bash CODE: npm init npm install express redis connect-redis express-session ---------------------------------------- TITLE: Using Laravel Cache with Redis DESCRIPTION: Example of using Laravel's cache functions with Redis as the cache driver. LANGUAGE: php CODE: Cache::put('key', 'value', now()->addMinutes(10)); $value = Cache::get('key'); ---------------------------------------- TITLE: Querying Redis Keys with Pattern Matching in Python DESCRIPTION: Examples of using the Redis KEYS command to retrieve keys matching specific patterns. Shows both prefix-based pattern matching and retrieving all keys. Note that this command should be used with caution in production environments due to potential blocking issues. LANGUAGE: python CODE: keys = redis.keys("prefix*") LANGUAGE: python CODE: keys = redis.keys("*") ---------------------------------------- TITLE: Retrieving Multiple Random Hash Fields with Redis HRANDFIELD DESCRIPTION: Example showing how to retrieve multiple random fields from a hash using the count parameter. Returns an array of specified number of random field names. LANGUAGE: typescript CODE: await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const randomFields = await redis.hrandfield("key", 2); console.log(randomFields); // ["id", "username"] or any other combination ---------------------------------------- TITLE: Creating Phoenix Home Page Template with Weather Form DESCRIPTION: HTML template for the home page featuring a form for location input and conditional display of weather information. This template will show different content based on parameters passed to it. LANGUAGE: html CODE: <.flash_group flash={@flash} />

Redix Demo

<%= if @text do %> <%= @text %> <% end %> <%= if @weather do %>
<%= if @location do %> Location: <%= @location %> <% end %>

Weather: <%= @weather %> °C

<% end %>
---------------------------------------- TITLE: Redis Cache Retrieval in Elixir using Redix DESCRIPTION: Method to fetch weather data from Redis cache using Redix. Returns decoded JSON data if found, or appropriate error responses if not found or on failure. LANGUAGE: elixir CODE: defp fetch_weather_from_cache(location) do case Redix.command(:redix, ["GET", "weather:#{location}"]) do {:ok, nil} -> {:error, :not_found} {:ok, cached_weather_json} -> {:ok, Jason.decode!(cached_weather_json)} {:error, _reason} -> {:error, "Failed to fetch weather data from cache."} end end ---------------------------------------- TITLE: Installing Upstash Redis in Cloudflare Worker Project DESCRIPTION: This command installs the Upstash Redis package in the Cloudflare Worker project directory. LANGUAGE: shell CODE: cd greetings-cloudflare npm install @upstash/redis ---------------------------------------- TITLE: Executing FLUSHALL Command in Redis using Python DESCRIPTION: Demonstrates how to use the FLUSHALL command in Redis using Python. The command deletes all keys permanently. It can be executed synchronously (default) or asynchronously using the 'flush_type' argument. LANGUAGE: python CODE: redis.flushall() LANGUAGE: python CODE: redis.flushall(flush_type="ASYNC") ---------------------------------------- TITLE: Checking Keyspace Notification Configuration in Upstash Redis DESCRIPTION: These commands demonstrate how to check the current configuration of keyspace and keyevent notifications using the CONFIG GET command. LANGUAGE: bash CODE: curl -X POST \ -d '["CONFIG", "GET", "notify-keyspace-events"]' \ -H "Authorization: Bearer $UPSTASH_REDIS_REST_TOKEN" \ $UPSTASH_REDIS_REST_URL LANGUAGE: bash CODE: redis-cli --tls -u $UPSTASH_REDIS_CLI_URL config get notify-keyspace-events ---------------------------------------- TITLE: Authenticating with Upstash Redis REST API using Bearer Token DESCRIPTION: Example of how to send a Redis SET command to Upstash using curl with an Authorization header containing a Bearer token. This command sets the key 'foo' to value 'bar'. LANGUAGE: shell CODE: curl https://us1-merry-cat-32748.upstash.io/set/foo/bar \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ---------------------------------------- TITLE: Outputting Upstash Database Credentials DESCRIPTION: Output configuration blocks to expose the database endpoint, port, and password. These values can be referenced from the created database resource. LANGUAGE: hcl CODE: output "endpoint" { value = "${upstash_database.mydb.endpoint}" } output "port" { value = "${upstash_database.mydb.port}" } output "password" { value = "${upstash_database.mydb.password}" } ---------------------------------------- TITLE: Adding Redix Dependencies to mix.exs DESCRIPTION: Adding Redix and CaStore dependencies to the Phoenix project to enable Redis connection capabilities. LANGUAGE: elixir CODE: defp deps do [ {:redix, "~> 1.1"}, {:castore, ">= 0.0.0"} ] end ---------------------------------------- TITLE: Creating Phoenix App Without Ecto Database DESCRIPTION: Command to create a new Phoenix application without the default Ecto database, since we'll only use Redis for storage. LANGUAGE: bash CODE: mix phx.new redix_demo --no-ecto ---------------------------------------- TITLE: Installing upstash-redis Package with npm DESCRIPTION: Command to install the upstash-redis npm package which is required to use the Redis client in your application. LANGUAGE: bash CODE: npm install @upstash/redis ---------------------------------------- TITLE: Listening to All Keyspace Notification Channels in Upstash Redis DESCRIPTION: This command uses redis-cli to subscribe to all keyspace notification channels, allowing you to test the effect of the previous configuration change. LANGUAGE: bash CODE: redis-cli --tls -u $UPSTASH_REDIS_CLI_URL --csv psubscribe '__key*__:*' ---------------------------------------- TITLE: Implementing Token Bucket Ratelimiting with Upstash Redis in Python DESCRIPTION: Sets up a Token Bucket ratelimiter with 10 maximum tokens, refilling at a rate of 5 tokens every 10 seconds. This algorithm models a bucket of tokens that refills at a constant rate, allowing for controlled bursts of traffic. LANGUAGE: python CODE: from upstash_ratelimit import Ratelimit, TokenBucket from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=TokenBucket(max_tokens=10, refill_rate=5, interval=10), ) ---------------------------------------- TITLE: Using SCARD Command in Redis with Python DESCRIPTION: Demonstrates how to add elements to a set using SADD and then get the set cardinality using SCARD. The example shows adding three elements and verifying the set size is 3. LANGUAGE: python CODE: redis.sadd("key", "a", "b", "c"); assert redis.scard("key") == 3 ---------------------------------------- TITLE: Popping the Last Element from a JSON Array in Redis DESCRIPTION: Removes and returns the last element from a JSON array at the specified path. This is the default behavior of JSON.ARRPOP when no index is provided. LANGUAGE: python CODE: element = redis.json.arrpop("key", "$.path.to.array") ---------------------------------------- TITLE: Installing Required Dependencies for Flask and Upstash Redis DESCRIPTION: Commands to install Flask web framework and Upstash Redis client using pip package manager. LANGUAGE: shell CODE: pip install flask pip install upstash-redis ---------------------------------------- TITLE: Implementing Redis Counter in Next.js API Route DESCRIPTION: TypeScript code for a Next.js API route that uses Upstash Redis to increment and retrieve a counter. This serverless function demonstrates how to interact with Redis in a Next.js App Router setup. LANGUAGE: typescript CODE: import { Redis } from "@upstash/redis"; import { NextResponse } from "next/server"; const redis = Redis.fromEnv(); export async function GET() { const count = await redis.incr("counter"); return NextResponse.json({ count }); } export const dynamic = 'force-dynamic' ---------------------------------------- TITLE: Installing Upstash Redis via npm DESCRIPTION: This snippet demonstrates how to install the @upstash/redis package using npm. LANGUAGE: bash CODE: npm install @upstash/redis ---------------------------------------- TITLE: Importing and Configuring Upstash Rate Limit SDK in TypeScript DESCRIPTION: This code demonstrates how to import the Rate Limit SDK and create a new instance with specific configuration options. It sets up rate limiting for 10 requests per 10 seconds using the default Redis configuration. LANGUAGE: typescript CODE: import { Ratelimit } from "@upstash/ratelimit" const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, prefix: "@upstash/ratelimit", }) ---------------------------------------- TITLE: Viewing Koyeb Application Runtime Logs DESCRIPTION: Command to track the runtime logs of a Koyeb service using the Koyeb CLI with continuous tracking enabled. LANGUAGE: bash CODE: koyeb service logs example-koyeb-upstash/example-koyeb-upstash -t runtime ---------------------------------------- TITLE: Using Redis TYPE Command in Python DESCRIPTION: Demonstrates how to use the TYPE command to check the data types of different Redis keys. Shows examples with string and list types, as well as checking non-existent keys which return 'none'. LANGUAGE: python CODE: redis.set("key1", "Hello") assert redis.type("key1") == "string" redis.lpush("key2", "Hello") assert redis.type("key2") == "list" assert redis.type("non-existent-key") == "none" ---------------------------------------- TITLE: Executing Cached Lua Script Using EVALSHA_RO in TypeScript DESCRIPTION: Example demonstrating how to execute a cached read-only Lua script using its SHA1 hash. The script takes no keys and a single argument 'hello'. The command returns the same value that was passed as the argument. LANGUAGE: typescript CODE: const result = await redis.evalshaRo("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", [], ["hello"]); console.log(result) // "hello" ---------------------------------------- TITLE: Redis Counter Implementation DESCRIPTION: AWS Lambda handler implementation for a counter function using Upstash Redis to increment and return a counter value. LANGUAGE: javascript CODE: const { Redis } = require('@upstash/redis'); const redis = Redis.fromEnv(); exports.counter = async (event) => { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ---------------------------------------- TITLE: Creating Next.js App and Installing Dependencies DESCRIPTION: Commands to create a new Next.js application with App Router and install the @upstash/redis package. LANGUAGE: shell CODE: npx create-next-app@latest cd my-app npm install @upstash/redis ---------------------------------------- TITLE: Installing Upstash Redis Typescript SDK DESCRIPTION: This snippet shows how to install the Upstash Redis Typescript SDK using npm. It's the first step in setting up the SDK for use in a Typescript project. LANGUAGE: bash CODE: npm install @upstash/redis ---------------------------------------- TITLE: Installing Serverless Framework DESCRIPTION: Command to install the Serverless framework globally using npm. LANGUAGE: text CODE: npm install -g serverless ---------------------------------------- TITLE: Installing upstash-redis-dump CLI Tool DESCRIPTION: Command to install the upstash-redis-dump tool globally via npm package manager. LANGUAGE: bash CODE: npm install -g upstash-redis-dump ---------------------------------------- TITLE: Importing Ratelimit in Deno DESCRIPTION: This code imports the Ratelimit class from the @upstash/ratelimit package using Deno's import syntax. LANGUAGE: typescript CODE: import { Ratelimit } from "https://cdn.skypack.dev/@upstash/ratelimit@latest"; ---------------------------------------- TITLE: Setting up QStash Client for Message Publishing DESCRIPTION: Demonstrates how to initialize a QStash client and publish JSON messages to an API endpoint using the @upstash/qstash package. LANGUAGE: typescript CODE: import { Client } from "@upstash/qstash"; const c = new Client({ token: process.env.QSTASH_TOKEN, }); const res = await c.publishJSON({ url: "https://my-api...", body: { hello: "world", }, }); ---------------------------------------- TITLE: Creating Serverless Framework Project DESCRIPTION: Interactive CLI command output showing the creation of a new Serverless Framework project with AWS Node.js HTTP API template. LANGUAGE: shell CODE: ➜ tutorials > ✗ serverless Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ✔ Select A Template: · AWS / Node.js / HTTP API ✔ Name Your Project: · counter-serverless ✔ Template Downloaded ✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · counter-serverless Your new Service "counter-serverless" is ready. Here are next steps: • Open Service Directory: cd counter-serverless • Install Dependencies: npm install (or use another package manager) • Deploy Your Service: serverless deploy ---------------------------------------- TITLE: Initializing Fastly Compute Project with CLI DESCRIPTION: Command-line interactions to set up a new Fastly Compute@Edge project using the JavaScript empty starter template. LANGUAGE: shell CODE: fastly compute init ---------------------------------------- TITLE: Initializing Azure Functions Project with TypeScript DESCRIPTION: Command to initialize a new Azure Functions project with TypeScript support LANGUAGE: shell CODE: func init --typescript ---------------------------------------- TITLE: Setting Upstash Redis Environment Variables DESCRIPTION: Shell commands to export Upstash Redis credentials as environment variables for use in the Lambda function. LANGUAGE: shell CODE: export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Installing Laravel CLI with Composer DESCRIPTION: Command to globally install the Laravel installer using Composer package manager. LANGUAGE: shell CODE: composer global require laravel/installer ---------------------------------------- TITLE: Executing Cached Lua Script with EVALSHA_RO in Python DESCRIPTION: Example showing how to execute a cached read-only Lua script using its SHA1 hash with the EVALSHA_RO command. The script is referenced by its SHA1 hash 'fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb' and takes a single argument 'hello'. LANGUAGE: python CODE: result = redis.evalsha_ro("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", args=["hello"]) assert result = "hello" ---------------------------------------- TITLE: Using SETRANGE Command in Redis with TypeScript DESCRIPTION: This example demonstrates how to use the SETRANGE command in Redis using TypeScript. It sets an initial value for a key, then modifies a portion of it using SETRANGE, and finally logs the new length of the modified value. LANGUAGE: typescript CODE: await redis.set("key", "helloworld") const length = await redis.setrange("key", 5, "redis"); console.log(length); // 10 // The value of "key" is now "helloredis" ---------------------------------------- TITLE: Testing Session Management Implementation with Python Requests DESCRIPTION: Python script to test the FastAPI session management implementation, including login, profile access, logout, and post-logout profile access attempts. LANGUAGE: python CODE: import requests base_url = "http://127.0.0.1:8000" # Test login response = requests.post(f"{base_url}/login/", json={"username": "abdullah"}) print("Login Response:", response.json()) # In the browser, you don't need to set cookies manually. The browser will handle it automatically. session_cookie = response.cookies.get("session_id") # Test profile profile_response = requests.get(f"{base_url}/profile/", cookies={"session_id": session_cookie}) print("Access Profile Response:", profile_response.json()) # Test logout logout_response = requests.post(f"{base_url}/logout/", cookies={"session_id": session_cookie}) print("Logout Response:", logout_response.json()) # Test profile after logout profile_after_logout_response = requests.get(f"{base_url}/profile/", cookies={"session_id": session_cookie}) print("Access Profile After Logout Response:", profile_after_logout_response.text) ---------------------------------------- TITLE: Creating Project Directory for AWS CDK DESCRIPTION: Creates a new directory for the CDK project and initializes it with TypeScript. LANGUAGE: shell CODE: mkdir counter-cdk && cd counter-cdk LANGUAGE: shell CODE: cdk init app --language typescript ---------------------------------------- TITLE: Creating Azure Function App DESCRIPTION: Azure CLI command to create a new function app with Node.js runtime LANGUAGE: shell CODE: az functionapp create --resource-group AzureFunctionsQuickstart-rg --consumption-plan-location --runtime node --runtime-version 18 --functions-version 4 --name --storage-account ---------------------------------------- TITLE: Setting Upstash Redis Environment Variables DESCRIPTION: Shell commands to export Upstash Redis connection credentials as environment variables. LANGUAGE: shell CODE: export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ---------------------------------------- TITLE: Installing Node.js Dependencies DESCRIPTION: Command to install the dependencies specified in package.json. LANGUAGE: shell CODE: npm install ---------------------------------------- TITLE: Setting Single Field in Redis Hash using HSET DESCRIPTION: Demonstrates how to set a single field-value pair in a Redis hash data structure. The command returns 1 indicating one field was added. LANGUAGE: python CODE: # Set a single field assert redis.hset("myhash", "field1", "Hello") == 1