> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://help.squarecloud.app/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# Redis: caching and session management

# Redis: Caching and Session Management

In high-performance applications, every millisecond counts. **Redis** acts as an ultra-fast storage layer that sits between your user and your persistent database (such as PostgreSQL or MySQL). In this article, we will explore Redis's two most vital functions: Caching and Session Management.

---

## 1. What Is Caching and Why Use It?

Caching is the process of storing the results of expensive operations (such as a complex database query or an external API response) in a fast-access location.

### Advantages:
* **Latency Reduction:** Redis responds in microseconds.
* **Resource Savings:** Prevents your primary database from processing the same information repeatedly.
* **Scalability:** Allows your application to support more concurrent users with the same hardware.

**Practical Example (TTL):**
One of the most powerful features is **TTL (Time To Live)**. You can save data and tell Redis: "Delete this in 600 seconds". This ensures your cache doesn't stay "stale" forever.

---

## 2. Session Management

When you have an application that scales (with multiple containers or shards), you cannot save user session data (such as a shopping cart or login state) in the local process memory. If the user hits a different container, they will lose everything.

Redis resolves this by serving as a **centralized source of truth**:
1. The user logs in.
2. Session data is saved in Redis with a unique ID.
3. This ID is sent to the user via a Cookie.
4. In any future request, any instance of your application can query Redis using this ID to know who the user is.

---

## 3. Connecting to Square Cloud

To connect your application to Square Cloud's Redis, you will need the data provided in your database tab:

* **Host:** `square-cloud-db-id.squareweb.app` (`id` is your instance ID, already included in the copied URL).
* **Port:** The port provided in the dashboard.
* **Password:** The password generated during instance creation.
* **Protocol:** Remember to use `rediss://` (with two 's') for secure connections with TLS/SSL.

---

## 4. Technical Implementation

### In Node.js (using `ioredis`)
```javascript
import { createClient } from "redis";
import fs from "fs";

const client = createClient({
  url: "rediss://default:JTI6bNRaws1Z1jokWU8mRfoW@square-cloud-db-{id}.squareweb.app:{port}",
  socket: {
    tls: true,
    ca: fs.readFileSync("ca-certificate.crt")
  },
});

// Saving to cache for 1 hour (3600 seconds)
await redis.set('usuario:123:perfil', JSON.stringify(perfil), 'EX', 3600);

// Retrieving from cache
const cache = await redis.get('usuario:123:perfil');
```

### In Python (using `redis-py`)
```python
import redis
import os
import ssl
from pathlib import Path

ca_cert_path = Path(__file__).with_name("ca-certificate.crt")
r = redis.from_url(
    "rediss://default:JTI6bNRaws1Z1jokWU8mRfoW@square-cloud-db-{id}.squareweb.app:{port}",
    decode_responses=True,
    ssl_cert_reqs=ssl.CERT_REQUIRED,
    ssl_ca_certs=str(ca_cert_path)
)

# Defining a session with expiration
r.setex("sessao:token_abc", 1800, "usuario_id_45")

# Fetching the session
user_id = r.get("sessao:token_abc")
```

---

## 5. Best Practices

* **Key Naming:** Use colons (`:`) to organize names, such as `app:v1:user:123`. This makes it easier to visualize in management tools.
* **Avoid Giant Keys:** Redis is fast, but reading a 100MB key will still take time. Try to keep objects small.
* **Monitor Memory:** Redis stores everything in RAM. Make sure to allocate enough memory to store data without pushing the limit.