# Caching in Kxreaper

_This page explains how caching works in Kxreaper._

Because cloud storage has higher latency, the `objstor` module in KDB-X can cache the requests results on a local high-performance disk. There is a limit on how much data can be added to the cache. This is controlled by the `KX_OBJSTR_CACHE_SIZE` environment variable.

When files are first retrieved from cloud storage, they are automatically stored in the local cache. Subsequent requests for the same data is then retrieved from the local cache instead of cloud storage, reducing both query time and transfer costs.

KDB-X only uses the local cache if the environment variable `KX_OBJSTR_CACHE_PATH` is defined.

This variable sets the path to the directory where cached files are stored. For example:
```bash
export KX_OBJSTR_CACHE_PATH=/myfastssd/kxs3cache
```

Temporary files are written under this directory, and KDB-X requires write permission. Cached files are stored under a subdirectory as `$KX_OBJSTR_CACHE_PATH/objects`.

> **Important — Shared cache**
>
>
> If multiple KDB-X instances are using the same HDB (historical database), they should all share a single cache directory.
>
The local cache is not cleared upon KDB-X start-up or shutdown.

It can only be deleted manually once all processes using the cache have stopped. To manage disk usage, use [Kxreaper](#kxreaper) to manage eviction from the cache folder. Without Kxreaper, the local cache continues to grow with each new dataset retrieved from object storage.

## Kxreaper

Kxreaper is a command-line application that manages the amount of object storage data cached on local disk.

Kxreaper can run as a daemon and takes two arguments:

- the cache root path
- an integer representing the size to limit the cache to in MB

Kxreaper continuously monitors file access within the specified directory and enforces a size limit by deleting files based on a Least Recently Used (LRU) algorithm. Any file moved into this directory becomes a candidate for deletion, as this area is **exclusively** used by KDB-X.

Files written by KDB-X in this area are first created as `filename$`. Once writing completes, they are renamed to the final filename. At this point, the OS notifies Kxreaper of this addition. If the cache exceeds its configured limit, Kxreaper deletes the least recently used files to free space.

On startup, Kxreaper scans the directory and deletes the oldest files if the total size exceeds the configured limit.

If Kxreaper gets out of sync with the filesystem - for example, after manual cache file deletions - you can manually trigger a rescan by sending a [`SIGHUP`](https://en.wikipedia.org/wiki/SIGHUP){target=_blank} signal to the Kxreaper process. If Kxreaper becomes too slow to process disk notifications, it rescans automatically.

> **Warning — Using Network Access Storage (NAS)**
>
>
> When using NAS, the Kxreaper process should run on the same machine as the HDB reader process, which is why NAS is not a recommended setup. For optimal performance, the cache should be on locally attached storage.
>
### Example

The following example runs Kxreaper as a daemon with both `STDOUT` and `STDERR` redirected to the system log:
```bash
kxreaper $KX_OBJSTR_CACHE_PATH 5000 2>&1 | logger &
```

View the log with:
```bash
sudo tail /var/log/syslog
```

Alternatively, redirect the output to a log file:
```bash
kxreaper $KX_OBJSTR_CACHE_PATH 5000 2>&1 > reaper.log &
```

### File storage in the kxreaper cache

The cache splits each Amazon S3 object into 2 MiB blocks and stores each block that is read as a separate file.

> **Note — Trace object storage requests**
>
> Set the `KX_TRACE_OBJSTR` environment variable to track whether a request retrieves data from Amazon S3 or the kxreaper cache.
>
The following example first retrieves data from Amazon S3:
```q
/ retrieve data from s3
q)getenv`KX_TRACE_OBJSTR
,"1"
q)select from quote where date=max date
Requesting bytes=0-2097151 from https://mybucket.amazonaws.com/db/2026.11.09/quote/sym
Requesting bytes=0-2097151 from https://mybucket.amazonaws.com/db/2026.11.09/quote/time
Requesting bytes=0-2097151 from https://mybucket.amazonaws.com/db/2026.11.09/quote/bid
...
sym  time                 bid
--------------------------------
AAPL 0D09:30:00.080414781 266.89
AAPL 0D09:30:00.105617515 266.82
AAPL 0D09:30:00.152900280 266.79
AAPL 0D09:30:00.182803286 266.8
..
/ retrieve from the cache
q)select sym,time,bid from quote where date=max date
sym  time                 bid
--------------------------------
AAPL 0D09:30:00.080414781 266.89
AAPL 0D09:30:00.105617515 266.82
AAPL 0D09:30:00.152900280 266.79
AAPL 0D09:30:00.182803286 266.8
..
```

The cache stores each column as its own set of block files. Three columns mean three separate sets, with no sharing between them.

For example, assume that the `sym`, `time`, and `bid` columns are each 10 MiB in this partition. The query creates five 2 MiB block files for each column, for a total of 15 files:
```bash
$KX_OBJSTR_CACHE_PATH/objects/<escaped path of quote/sym>        0-2097152, 2097152-2097152, … 8388608-2097152   (5 files)
$KX_OBJSTR_CACHE_PATH/objects/<escaped path of quote/time>       0-2097152, 2097152-2097152, … 8388608-2097152   (5 files)
$KX_OBJSTR_CACHE_PATH/objects/<escaped path of quote/bid>        0-2097152, 2097152-2097152, … 8388608-2097152   (5 files)
```

### Clear the kxreaper cache

If the underlying data in Amazon S3 changes, you must manually clear the corresponding data from the kxreaper cache.

For information about deleting the entire cache, see [kxreaper](#kxreaper).

To clear only a subset of the kxreaper cache, use a `find` command that matches the corresponding bucket and prefix. For example, the following commands find and delete the cached data for the `quote` table in the `2026.11.09` partition:

> **Warning — Stop queries on the affected data first**
>
>
> Make sure no queries are reading the affected data while you delete it from the cache. Otherwise a single query can read some blocks from the old cached copy and others from the updated object in Amazon S3, and return inconsistent results.
>
```bash
# trial run to view what is present
find "$KX_OBJSTR_CACHE_PATH/objects" -maxdepth 1 -name 's3%3A%2F%2Fmybucket%2Fdb%2F2026.11.09%2Fquote%2F*' -print
# remove from the kxreaper cache
find "$KX_OBJSTR_CACHE_PATH/objects" -maxdepth 1 -name 's3%3A%2F%2Fmybucket%2Fdb%2F2026.11.09%2Fquote%2F*' -delete
```

The components of the `-name` pattern have the following meanings:

- `s3%3A%2F%2F` represents `s3://`.
- `mybucket%2Fdb%2F2026.11.09%2Fquote%2F` represents the bucket and prefix, with each `/` escaped.
- The trailing `%2F` after `quote` represents the escaped slash, so the match stops at the quote directory. Without it, `quote*` would also match a table called `quotes` or `quote2`.
- The final `*` is a `find` wildcard. It matches the object name (`ask`, `bid`, `.d`, and so on), the block offset, and the `-2097152` block size.

Deleting cached blocks does not refresh the object metadata (the list of objects and their sizes) that each KDB-X process holds in memory. If objects were added, removed, or changed size, also [refresh the metadata](overview.md#metadata-in-object-storage) in each process that reads the data.

### Troubleshooting

If you observe the following error:

`inotify_init: Too many open files`

check the values in:
```txt
/proc/sys/fs/inotify/max_queued_events
/proc/sys/fs/inotify/max_user_instances
/proc/sys/fs/inotify/max_user_watches
```

Increase them if needed to match the number of files that may be cached. For example:
```bash
echo 8192 >> /proc/sys/fs/inotify/max_user_instances
echo 8192 >> /proc/sys/fs/inotify/max_user_watches
```

If the environment variable `KX_CACHE_REAPER_TRACE` is set, Kxreaper prints tracing information while processing events.
