> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Response Compression

> The Swarms API automatically compresses HTTP responses using Zstandard, LZ4, or GZip to reduce payload size and improve response times.

The Swarms API uses intelligent response compression to significantly reduce payload sizes and improve response times. Responses are automatically compressed when beneficial, reducing bandwidth usage and speeding up data transfer.

The API implements a dynamic compression middleware that automatically compresses HTTP responses based on:

* **Response size**: Only compresses bodies larger than 500 bytes and no larger than 8 MiB
* **Client support**: Negotiates the algorithm via the `Accept-Encoding` header (including q-values)
* **Compression efficiency**: Only applies compression if it actually reduces the response size

## Supported Compression Algorithms

The server's preference order (highest first) is Zstandard, then LZ4, then GZip. Among encodings a client rates equally, the server picks the highest one in this order; if a client's `Accept-Encoding` doesn't name any of these explicitly but accepts `*`, GZip is used since every client can decode it.

| Algorithm | Server Preference | Notes |
| - | - | - |
| **Zstandard (`zstd`)** | 1st | Compression level 3 |
| **LZ4 (`lz4`)** | 2nd | Very fast, used when a client explicitly requests it and can decode LZ4 frames |
| **GZip (`gzip`)** | 3rd / fallback | Compression level 6. Universal browser and client support — what most clients receive |

<Info>
  Standard HTTP clients advertise `gzip` (not `zstd` or `lz4`) by default, so in practice most responses are GZip-compressed. Zstandard or LZ4 are only used when a client explicitly sends `zstd` or `lz4` in `Accept-Encoding` and can decode that format.
</Info>

## How It Works

### Automatic Compression

The compression middleware automatically:

1. **Parses client preferences**: Reads the `Accept-Encoding` header, ordering encodings by their q-values. An encoding with `q=0` is explicitly excluded; a `*` wildcard means any encoding is acceptable
2. **Selects the algorithm**: Walks the client's encodings in preference order and picks the first one the server supports. If only `*` matches, GZip is used, since every client can decode it
3. **Checks response size**: Only compresses bodies larger than 500 bytes and no larger than 8 MiB
4. **Validates compression**: Only applies if the compressed size is smaller than the original
5. **Sets headers**: Sets `Content-Encoding`, updates `Content-Length` to the compressed size, and appends `Accept-Encoding` to the `Vary` header

### Compression Flow

```
Request → Parse Accept-Encoding (q-values) → Select Algorithm →
Check Size (500 bytes < body ≤ 8 MiB) → Compress → Validate → Return Compressed Response
```

### Responses That Are Never Compressed

The middleware passes these responses through unmodified:

* **Streaming responses**, including Server-Sent Events (`text/event-stream`) — events must be flushed immediately, not buffered
* **Already-encoded responses** — anything that already has a `Content-Encoding` header is never re-compressed
* **Small responses** — bodies of 500 bytes or less
* **Large responses** — bodies over 8 MiB (bounds server buffering memory)
* **Responses where compression doesn't help** — if the compressed body isn't smaller, the original is returned

### Client Preferences

The API respects client compression preferences through the `Accept-Encoding` header, including q-values:

```bash theme={null}
Accept-Encoding: zstd, lz4, gzip;q=0.8, br;q=0
```

In this example the client accepts Zstandard and LZ4 at equal (default) priority, GZip at lower priority, and explicitly refuses Brotli (`q=0`). The middleware:

* Honors q-value ordering when choosing among supported methods
* Within one quality tier, breaks ties using the server's own preference order (Zstandard, then LZ4, then GZip)
* Treats `q=0` as "do not use this encoding"
* Treats `*` as "any encoding" and responds with GZip, since every client can decode it
* Returns the response uncompressed if no supported encoding is acceptable

## Benefits

### Performance Improvements

| Benefit | Description |
| - | - |
| **Reduced Bandwidth** | Smaller payloads mean less data transfer |
| **Faster Response Times** | Less data to transmit results in quicker responses |
| **Lower Latency** | Especially beneficial for large JSON responses |
| **Cost Savings** | Reduced bandwidth usage for both client and server |

### Automatic Optimization

* **No configuration required**: Compression is automatic and transparent
* **Smart fallback**: Automatically uses the best available method
* **Size validation**: Only compresses when it actually helps
* **Header management**: Properly sets compression headers for client compatibility

## Usage

### Standard HTTP Requests

Compression works automatically with all API endpoints. No special configuration is needed — standard clients already send `Accept-Encoding: gzip` and decompress transparently:

```bash theme={null}
curl --compressed \
     -H "x-api-key: your-api-key" \
     https://api.swarms.world/v1/models
```

### Client Libraries

Most HTTP clients automatically request and decompress GZip. Only opt into Zstandard or LZ4 if your client can decode that format:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import requests

    # requests sends "Accept-Encoding: gzip, deflate" automatically
    # and transparently decompresses the response.
    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={"x-api-key": "your-api-key"},
        json={
            "agent_config": {
                "agent_name": "example",
                "model_name": "gpt-4o-mini",
                "max_loops": 1,
            },
            "task": "Your task here",
        },
    )

    data = response.json()
    ```
  </Tab>

  <Tab title="Python (Zstandard)">
    ```python theme={null}
    import json

    import requests
    import zstandard

    # Explicitly request Zstandard. requests does NOT decompress zstd,
    # so decode the raw body manually.
    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={
            "x-api-key": "your-api-key",
            "Accept-Encoding": "zstd",
        },
        json={
            "agent_config": {
                "agent_name": "example",
                "model_name": "gpt-4o-mini",
                "max_loops": 1,
            },
            "task": "Your task here",
        },
        stream=True,
    )

    body = response.raw.read()
    if response.headers.get("Content-Encoding") == "zstd":
        body = zstandard.ZstdDecompressor().decompress(body)

    data = json.loads(body)
    ```
  </Tab>

  <Tab title="Python (LZ4)">
    ```python theme={null}
    import json

    import lz4.frame
    import requests

    # Explicitly request LZ4. requests does NOT decompress LZ4,
    # so decode the raw body manually.
    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={
            "x-api-key": "your-api-key",
            "Accept-Encoding": "lz4",
        },
        json={
            "agent_config": {
                "agent_name": "example",
                "model_name": "gpt-4o-mini",
                "max_loops": 1,
            },
            "task": "Your task here",
        },
        stream=True,
    )

    body = response.raw.read()
    if response.headers.get("Content-Encoding") == "lz4":
        body = lz4.frame.decompress(body)

    data = json.loads(body)
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    // fetch negotiates gzip automatically and decompresses transparently.
    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
      method: 'POST',
      headers: {
        'x-api-key': 'your-api-key',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        agent_config: {
          agent_name: 'example',
          model_name: 'gpt-4o-mini',
          max_loops: 1
        },
        task: 'Your task here'
      })
    });

    const data = await response.json();
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    # --compressed sends "Accept-Encoding: gzip" and decodes the response
    curl --compressed \
         -X POST https://api.swarms.world/v1/agent/completions \
         -H "x-api-key: your-api-key" \
         -H "Content-Type: application/json" \
         -d '{
           "agent_config": {
             "agent_name": "example",
             "model_name": "gpt-4o-mini",
             "max_loops": 1
           },
           "task": "Your task here"
         }'
    ```
  </Tab>
</Tabs>

### Response Headers

Compressed responses include these headers:

```http theme={null}
Content-Encoding: gzip
Content-Length: 1234
Vary: Accept-Encoding
```

* **Content-Encoding**: Indicates the compression method used (`gzip`, `lz4`, or `zstd`)
* **Content-Length**: Updated to the compressed size (smaller than the original)
* **Vary**: `Accept-Encoding` is appended so caches store separate variants per encoding

## Compression Statistics

The middleware logs compression details (at debug level) for monitoring:

* Original response size
* Compressed response size
* Algorithm used

## Best Practices

### 1. Include Accept-Encoding Header

Make sure your client sends an `Accept-Encoding` header (most do by default):

```bash theme={null}
Accept-Encoding: gzip
```

Only add `zstd` or `lz4` if your client decodes those formats — e.g. `Accept-Encoding: zstd, lz4, gzip;q=0.8`.

### 2. Let Clients Handle Decompression

Most HTTP clients automatically decompress responses. Don't manually decompress unless necessary.

### 3. Monitor Response Sizes

Large responses benefit most from compression. The API automatically handles this optimization.

### 4. Use Modern Clients

Modern HTTP clients (requests, fetch, axios) automatically handle compression and decompression.

## Technical Details

### Size Thresholds

* **Minimum (500 bytes)**: Bodies of 500 bytes or less are not compressed — compression overhead exceeds the benefit for tiny payloads, where network latency is the bottleneck anyway
* **Maximum (8 MiB)**: Bodies larger than 8 MiB are passed through uncompressed to bound the memory used for buffering responses on the server

### Compression Method Selection

The middleware selects the compression method as follows:

1. **Client preference match**: Walks the client's `Accept-Encoding` entries in q-value order and uses the first method the server supports (`q=0` entries are skipped entirely)
2. **Wildcard support**: If the client accepts `*`, GZip is used, since every client can decode it
3. **No compression**: Returns the response uncompressed if no acceptable method is supported

### Error Handling

If compression fails:

* Original uncompressed response is returned
* No error is raised to the client
* Compression failure is logged for monitoring
* Client receives valid response regardless

## Compatibility

### Browser Support

All modern browsers support GZip compression automatically. Zstandard and LZ4 are not natively supported by browsers or most HTTP libraries — only request them if you decode the format yourself.

### API Clients

| Client | GZip Decompression | Zstandard Decompression | LZ4 Decompression |
| - | - | - | - |
| Python `requests` | Automatic | Manual (`zstandard.ZstdDecompressor`) | Manual (`lz4.frame.decompress`) |
| JavaScript `fetch` | Automatic | Manual | Manual |
| `curl` | Automatic with `--compressed` | Manual | Manual |
| `axios` | Automatic | Manual | Manual |
| `httpx` | Automatic | Manual (`zstandard.ZstdDecompressor`) | Manual (`lz4.frame.decompress`) |

## Summary

The Swarms API's automatic response compression:

* **Reduces bandwidth usage** by compressing responses
* **Improves response times** through smaller payloads
* **Works transparently** with no configuration needed
* **Supports Zstandard, LZ4, and GZip**, preferring Zstandard, then LZ4, when the client accepts them
* **Respects client preferences** via the Accept-Encoding header, including q-values (`q=0` excludes an encoding; `*` accepts any)
* **Only compresses when it helps** — bodies between 500 bytes and 8 MiB, and only if the result is actually smaller
* **Never touches streaming (SSE) or already-encoded responses**
* **Compatible with all clients** that support standard HTTP compression

<Note>
  Compression is automatic and requires no configuration. Simply make API requests as normal, and responses will be compressed when beneficial.
</Note>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.