# XADD

> Add entry to stream.

Use `XADD` to append an entry to a stream, creating the stream when it does not exist.

An entry is a set of field and value pairs identified by an ID of the form `<milliseconds>-<sequence>`. Passing `*` lets the server build the ID from the current time, which guarantees that IDs only ever increase; an explicit ID must be greater than the last one in the stream. The reply is the ID the entry was stored under. `NOMKSTREAM` skips creating a stream that does not exist yet and returns null instead.

The trimming options cap the stream in the same call, which is how a stream is kept from growing without bound. `MAXLEN` limits the number of entries and `MINID` drops entries with an ID below a threshold, which is the way to trim by age since IDs start with a timestamp. `~` makes the trim approximate, stopping at a convenient boundary, which is much cheaper than the exact `=` and is what most workloads should use; `LIMIT` caps how many entries a single call may evict.

`KEEPREF`, `DELREF`, and `ACKED` decide what happens to consumer group references of the entries that trimming removes: `KEEPREF`, the default, leaves those references in place, `DELREF` removes them as well, and `ACKED` only removes entries that every group has read and acknowledged.

## Syntax

```redis
XADD <key>
  [NOMKSTREAM]
  [KEEPREF | DELREF | ACKED]
  [(MAXLEN | MINID) [= | ~] <threshold> [LIMIT <count>]]
  (* | <id>) <field> <value> [<field> <value> ...]
```

## Arguments

| Argument | Required | Repeatable | Description |
| --- | --- | --- | --- |
| `<key>` | Yes | No | Redis key targeted by the command. |
| `NOMKSTREAM` | No | No | Do not create a missing stream. |
| `(KEEPREF \| DELREF \| ACKED)` | No | No | What happens to consumer-group references of the entries that trimming removes: `KEEPREF` (the default) leaves them in place, `DELREF` removes them from every group's pending list, and `ACKED` only removes entries that every group has read and acknowledged. |
| `(MAXLEN \| MINID) [= \| ~] <threshold> [LIMIT <count>]` | No | No | Trim the stream after the entry is added. `MAXLEN` caps the number of entries; `MINID` drops entries with a lower ID. `=` trims exactly and is the default; `~` trims approximately and is required before `LIMIT`, which caps how many entries a single call evicts. |
| `(* \| <id>)` | Yes | No | Entry ID: `*` lets the server generate one from the current time, or give an explicit `<milliseconds>-<sequence>` ID, which must be greater than the stream's last one. |
| `<field> <value>` | Yes | Yes | Field and the value to store in it. Repeat to set several fields in one call. |

## Response

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

| Protocol | Reply |
| --- | --- |
| RESP2 | Bulk string or Null bulk string or null array |
| RESP3 | Bulk string or Null |

<Note>
  Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.
</Note>

## Examples

TCP examples use the TLS `REDIS_URL` from the Upstash console. REST examples use `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.

<AccordionGroup>

<Accordion title="Redis CLI" icon="terminal">

```bash
XADD my-key * field value
```

</Accordion>

<Accordion title="@upstash/redis" icon="node-js" iconType="brands">

```ts
import { Redis } from "@upstash/redis";

const redis = Redis.fromEnv();

const result = await redis.xadd("mystream", "*", { name: "John Doe", age: 30 });
```

</Accordion>

<Accordion title="upstash_redis" icon="python" iconType="brands">

```python
from upstash_redis import Redis

redis = Redis.from_env()
result = redis.xadd("my-key", "*", {"field": "value"})
print(result)
```

</Accordion>

<Accordion title="ioredis" icon="node-js" iconType="brands">

```ts
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);
const result = await redis.xadd("my-key", "*", "field", "value");
console.log(result);
```

</Accordion>

<Accordion title="node-redis" icon="node-js" iconType="brands">

```ts
import { createClient } from "redis";

const client = await createClient({ url: process.env.REDIS_URL })
  .on("error", console.error)
  .connect();
const result = await client.xAdd("my-key", "*", { field: "value" });
console.log(result);
```

</Accordion>

<Accordion title="redis-py" icon="python" iconType="brands">

```python
import os
import redis

client = redis.from_url(os.environ["REDIS_URL"])
result = client.xadd("my-key", {"field": "value"})
print(result)
```

</Accordion>

<Accordion title="go-redis" icon="golang" iconType="brands">

```go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/redis/go-redis/v9"
)

func main() {
    opts, err := redis.ParseURL(os.Getenv("REDIS_URL"))
    if err != nil {
        panic(err)
    }
    client := redis.NewClient(opts)
    result, err := client.XAdd(context.Background(), &redis.XAddArgs{Stream: "my-key", Values: map[string]interface{}{"field": "value"}}).Result()
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
```

</Accordion>

<Accordion title="jedis" icon="java" iconType="brands">

```java
import java.net.URI;

import redis.clients.jedis.Jedis;

try (Jedis jedis = new Jedis(new URI(System.getenv("REDIS_URL")))) {
  Object result = jedis.xadd("my-key", redis.clients.jedis.StreamEntryID.NEW_ENTRY, java.util.Map.of("field", "value"));
  System.out.println(result);
}
```

</Accordion>

<Accordion title="redis-rs" icon="rust" iconType="brands">

```rust
use redis::TypedCommands;

fn main() -> redis::RedisResult<()> {
    let url = std::env::var("REDIS_URL").expect("REDIS_URL is not set");
    let client = redis::Client::open(url)?;
    let mut connection = client.get_connection()?;

    let result = connection.xadd("my-key", "*", &[("field", "value")])?;
    println!("{result:?}");
    Ok(())
}
```

</Accordion>

</AccordionGroup>
