# How to tune your cache settings

import Tabs from '~/components/tabs/Tabs'


Leverage the capabilities of [Cache](/en/documentation/products/build/applications/cache-settings/) to configure your application's [cache policies](/en/documentation/products/build/applications/cache-settings/), including expiration values at the edge or browser level, large file optimization to break large files into smaller chunks, and cache key segmentation based on HTTP methods, query strings, cookies, or device groups.

:::caution[warning]
Some cache features require the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) module to be active. If **Application Accelerator** is activated, data transfer could generate usage-related costs. Check the [pricing page](/en/documentation/products/pricing/) for more information.
:::

---

When you first [create an application](/en/documentation/products/start-with-a-template/), a cache setting variable will be created and activated by default. This guide will show you how to create and activate a brand new cache setting instance.

<Tabs client:visible>
    <Fragment slot="tab.console">Console</Fragment>
    <Fragment slot="tab.api">API</Fragment>

<Fragment slot="panel.console">
1. Access [Azion Console](/en/documentation/products/guides/how-to-access-azion-console/) > **Applications**.
2. Click the application you want to configure. 
3. Activate the **Application Accelerator** module to unlock advanced cache key configurations.
4. Click the **Save** button.
5. Navigate to the **Cache Settings** tab.
6. Click the **+ Cache Setting** button.
7. Give your cache setting a name.

**Cache Expiration Policies**

You can customize the cache Time To Live (TTL) in browsers and at the edge. This data is sent in requests and responses through the `Cache-Control` and `Expires` HTTP headers.

:::note
The TTL determined by the `max-age` directive in `Cache-Control`. If `Cache-Control` isn't present in the request or response, the timestamp sent in the `Expires` header determines the cache TTL. 
:::

1. In **Browser Cache**, select **Override cache settings** to determine a custom TTL value.
2. Add the TTL in seconds in the **Max Age (seconds)** field. For example: `432000` = 5 days.

In **Cache**, you can determine whether the edge should abide by the values sent in the `Cache-Control` and `Expires` headers.

You can choose to keep **Honor cache policies** selected to respect the TTL values sent in the headers by the origin or the application itself.

If your application isn't sending `Cache-Control` and `Expires` headers or the values aren't set correctly, you can determine a default maximum TTL for the cache to be maintained at the edge in the **Max Age (seconds)** field. If your application is sending these values, to override them:

3. In **Cache**, select **Override cache settings** to determine a custom TTL value.
4. Add the TTL in seconds in the **Max Age (seconds)** field. For example: `864000` = 10 days.

:::note
The maximum and default TTL values for the edge should be between `60` and `31536000` seconds (1 year). If you have the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) module activated, you can set this value to a minimum of `0`. Additionally, if you have the [Cache](/en/documentation/products/build/applications/cache/tiered-cache/) module activated and wish to maintain cache in the cache layer, you must set TTL to at least `3` seconds.

A TTL zero isn't the same as a cache bypass. For more details, read about the difference between these settings on the [Bypass Cache behavior](/en/documentation/products/build/applications/rules-engine/#bypass-cache) documentation.
:::

**Stale cache**

Azion provides the capability to serve stale content from the cache when the origin server is down or while the cache is being renewed. The **Stale cache** feature is enabled by default, allowing your application to continue serving the most recent cached content during these events.

**Large file optimization**

Instead of downloading a large content file and risking timeouts or connection terminations, [files can be fragmented](/en/documentation/products/build/applications/cache-settings/#large-file-optimization) into smaller pieces and cached on-demand.

5. In **Large file optimization**, enable the switch to activate.
6. The **Cache** layer is already selected by default. If you have the **Cache** module activated, you can also enable this feature for the cache layer.

:::note
The default fragment size is of `1024 kB`.
:::

**Application Accelerator**

This section lets you customize how cache varies based on HTTP methods, query string fields, cookies and device groups through [cache keys](/en/documentation/products/build/applications/cache-settings/#advanced-cache-key). You can choose to segment cache keys using these attributes to control how objects are stored and served from the cache.

:::caution[warning]
To enable all Application Accelerator functionalities, you must activate the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) module.
:::

To determine content variation in cache:

7. In **Cache vary by Method**, activate the **Enable caching for POST** switch to cache `POST` requests and the **Enable caching for OPTIONS** switch to cache `OPTIONS` requests.

8. In **Cache vary by Query String**, select **Content varies by some query string fields (Allowlist)**.
9. In **Query string fields**, add the value `city`.
  - This field is case‑sensitive and treats uppercase and lowercase letters differently when storing objects in the cache.

When a request is made to an application URL `xxxxxxxxxx.map.azionedge.net/page?city=12345`, the cache key for this URL will be different from cache keys made to `xxxxxxxxxx.map.azionedge.net/page` and any other queries appended to the URL.

:::tip
Use the **Content varies by query string, except for some fields (Blocklist)** option to do the reverse: keep all requests with query strings as different cache keys; the ones specified in **Query string fields** will be grouped into a single cache key.
:::

To disregard the order of the data sent in the query string and keep objects with the same query string values as a single cache key:

10. Enable the **Query String sort** switch.

11. In **Cache vary by Cookies**, select **Content varies by some cookies (Allowlist)**.
12. In **Cookie names**, add the value `cookie_name`.
  - This field is case‑sensitive and treats uppercase and lowercase letters differently when storing objects in the cache.

When a request is made to an application and the response from the origin sends a `Set‑Cookie` header, the objects in the `Cookie` request header that contain the name `cookie_name`, regardless of value, will be considered as a different object in cache from other requests.

:::tip
Use the **Content varies by cookies, with the exception of a few (Blacklist)** option to do the reverse: keep all requests with cookies as different cache keys; the ones specified in the **Cookie names** will be grouped into a single cache key.
:::

13. In **Cache vary by Devices**, select **Content varies by some device groups (Allowlist)**.
14. Click the **+ Add Device Group** button to add a device group and select it from the list.
15. Repeat the previous step for every device group you wish to specify a different cache key.

Once you've finished configuring your cache setting:

16. Click the **Save** button.

**Activating your cache setting**

The cache settings page now lists the newly created instance. However, this new cache setting isn't active in your application. You need to define what will trigger the implementation of the cache policies in your application. For this, you can use your application's [Rules Engine](/en/documentation/products/build/applications/rules-engine/).

The instructions below will help you create a rule in which any request from your users to `xxxxxxxxxx.map.azionedge.net/cache` will apply the cache setting you created.

1. Navigate to the **Rules Engine** tab.
2. Click the **+ Rule** button.
3. Give a name for your rule.
4. Select **Request Phase**.
5. Under the **Criteria** section, select the variable `${uri}`.

:::note
The `${uri}` variable may already be selected by default if you didn't activate the **Application Accelerator** module.
:::

6. As a comparison operator, select **is equal**.
7. As an argument, add `/cache`.
8. In the **Behaviors** section, select **Set Cache Policy** from the behavior list.
9. Select the new cache setting you created.
10. Click the **Save** button.
11. Wait a few minutes for the changes to propagate.

To verify how your content is being cached, you can [verify application cache indicators using Modheader for Google Chrome](/en/documentation/products/guides/check-page-cache-time/).
</Fragment>

<Fragment slot="panel.api">
1. Run the following `PATCH` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/) and the `<application_id>` variable with [your application ID](/en/documentation/products/guides/build/configure-main-settings/) to activate the [Application Accelerator](/en/documentation/products/build/applications/application-accelerator/) module:

```bash
curl --location --request PATCH 'https://api.azionapi.net/v4/edge_applications/<application_id>' \
--header 'Accept: application/json;' \
--header 'Content-Type: application/json' \
--header 'Authorization: Token [TOKEN VALUE]' \
--data '{
    "application_acceleration": true
}'
```

2. You'll receive a response with the updated value.
3. If you want to configure adaptive delivery for one of your [device groups](/en/documentation/products/guides/build/create-device-groups/), run the following `GET` request beforehand:

```bash
curl --location 'https://api.azionapi.net/v4/edge_application/applications/{application_id}/device_groups' \
--header 'Accept: application/json;' \
--header 'Authorization: Token [TOKEN VALUE]'
```

4. Copy the ID received in the response.
5. Run the following `POST` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/), the `<application_id>` variable with [your application ID](/en/documentation/products/guides/build/configure-main-settings/), and the `<device_group_id>` with the ID of the device group from the previous response, if needed:

```bash
curl --location 'https://api.azionapi.net/v4/edge_application/applications/<application_id>/cache_settings' \
--header 'Accept: application/json;' \
--header 'Content-Type: application/json' \
--header 'Authorization: Token [TOKEN VALUE]' \
--data '{
  "name": "/cache O60 O13660 Wcity Wcookie_name Wdg POST OPTIONS SLICE",
  "browser_cache": {
    "behavior": "override",
    "max_age": 60
  },
  "modules": {
    "edge_cache": {
      "behavior": "override",
      "max_age": 13660,
      "stale_cache": {
        "enabled": false
      },
      "large_file_cache": {
        "enabled": true,
        "offset": 1024
      }
    },
    "application_accelerator": {
      "cache_vary_by_method": [
        "post",
        "options"
      ],
      "cache_vary_by_querystring": {
        "behavior": "whitelist",
        "fields": [
          "city"
        ],
        "sort_enabled": false
      },
      "cache_vary_by_cookies": {
        "behavior": "whitelist",
        "cookie_names": [
          "cookie_name"
        ]
      },
      "cache_vary_by_devices": {
        "behavior": "whitelist",
        "device_group": [
          <device_group_id>
        ]
      }
    }
  }
}'
```

| Key | Description |
| --- | --- |
| `name` | Sets the string value as the name of the cache setting. |
| `browser_cache.behavior` | Defines the caching behavior for browsers. `"honor"` respects origin headers; `"override"` allows defining a custom TTL using `max_age`. |
| `browser_cache.max_age` | Maximum TTL (in seconds) for browser caching when `behavior` is set to `"override"`. |
| `modules.edge_cache.behavior` | Defines edge caching behavior. `"honor"` uses the origin's TTL headers, and `"override"` uses the `max_age` field instead. |
| `modules.edge_cache.max_age` | TTL (in seconds) for cache when overriding origin headers. |
| `modules.edge_cache.stale_cache.enabled` | Enables [stale cache](https://www.azion.com/en/documentation/products/build/applications/cache-settings/#stale-cache) to serve expired content temporarily while fetching updated content from the origin. |
| `modules.edge_cache.large_file_cache.enabled` | Enables [large file optimization](https://www.azion.com/en/documentation/products/build/applications/cache-settings/#large-file-optimization) by caching large files in fragments. |
| `modules.edge_cache.large_file_cache.offset` | Defines the fragment size (in kilobytes) for large file caching. Default is `1024`. |
| `modules.tiered_cache.topology` | Defines the topology used in cache: `"near-edge"` or `"near-origin"` (if supported). |
| `modules.application_accelerator.cache_vary_by_method` | List of HTTP methods (e.g., `["post", "options"]`) that should vary the cache key. |
| `modules.application_accelerator.cache_vary_by_querystring.behavior` | Defines how query strings affect cache variation. Options: `"ignore"`, `"whitelist"`, `"blacklist"`. |
| `modules.application_accelerator.cache_vary_by_querystring.fields` | List of query string fields to allow/block when varying cache (based on behavior). |
| `modules.application_accelerator.cache_vary_by_querystring.sort_enabled` | Enables sorting of query string parameters before computing cache keys. |
| `modules.application_accelerator.cache_vary_by_cookies.behavior` | Defines how cookies affect cache variation. Options: `"ignore"`, `"whitelist"`, `"blacklist"`. |
| `modules.application_accelerator.cache_vary_by_cookies.cookie_names` | List of cookie names to use for cache variation. |
| `modules.application_accelerator.cache_vary_by_devices.behavior` | Defines how device groups affect cache variation. Options: `"ignore"`, `"whitelist"`, `"blacklist"`. |
| `modules.application_accelerator.cache_vary_by_devices.device_group` | List of device group IDs used to vary cache content by user device. |

6. You'll receive a response similar to this:

```json
{
    "status": "pending",
    "data": {
        "id": <cache_settings_id>,
        "name": "/cache O60 O13660 Wcity Wcookie_name Wdg POST OPTIONS SLICE",
        "browser_cache": {
        "behavior": "override",
        "max_age": 60
    },
    "modules": {
        "edge_cache": {
        "behavior": "override",
        "max_age": 13660,
        "stale_cache": {
            "enabled": false
        },
        "large_file_cache": {
            "enabled": true,
            "offset": 1024
        }
        },
        "application_accelerator": {
        "cache_vary_by_method": [
            "post",
            "options"
        ],
        "cache_vary_by_querystring": {
            "behavior": "whitelist",
            "fields": ["city"
            ],
            "sort_enabled": false
        },
        "cache_vary_by_cookies": {
            "behavior": "whitelist",
            "cookie_names": [
            "cookie_name"
            ]
        },
        "cache_vary_by_devices": {
            "behavior": "whitelist",
            "device_group": [
            <device_group_id>
            ]
        }
        }
    }
  }
}
```

7. Run the following `POST` request in your terminal, replacing `[TOKEN VALUE]` with your [personal token](/en/documentation/products/guides/personal-tokens/), the `<application_id>` variable with [your application ID](/en/documentation/products/guides/build/configure-main-settings/), and the `<cache_setting_id>` variable with the cache setting ID received in the response:

```bash
curl --location 'https://api.azionapi.net/v4/edge_application/applications/<application_id>/request_rules' \
--header 'Accept: application/json;' \
--header 'Content-Type: application/json' \
--header 'Authorization: Token [TOKEN VALUE]' \
--data '{
    "name": "Set cache setting /cache",
    "behaviors": [
        {
            "name": "set_cache_policy",
            "target": "<cache_setting_id>"
        }
    ],
    "criteria": [
        [
            {
                "variable": "${uri}",
                "operator": "is_equal",
                "conditional": "if",
                "argument": "/cache"
            }
        ]
    ]
}'
```

8. You'll receive a response with the updated data.
9. Wait a few minutes for the changes to propagate.

To verify how your content is being cached, you can [verify application cache indicators using Modheader for Google Chrome](/en/documentation/products/guides/check-page-cache-time/).

:::tip
Check the [Azion API documentation](https://api.azion.com/) and the [OpenAPI specification](https://github.com/aziontech/azionapi-openapi/) to know more about all features available via API.
:::
</Fragment>

</Tabs>