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

# Caching

> Typed Redis cache examples, stampede protection, and cache boundaries.

# Caching

## Complete Example

```ts theme={null}
import { loadService } from '@hile/core'
import redisService from '@hile/ioredis'
import { Cache, defineCache, RedisCache } from '@hile/cache'

const userProfileCache = defineCache(
  'user:{id:string}:profile',
  async ({ id }) => {
    const profile = await loadProfileFromDatabase(id)
    if (!profile) return new Cache(undefined)
    return new Cache(profile).setExpire(300)
  },
  {
    singleflight: { ttl: 10_000, wait: 10_000 },
    stale: { ttl: 60 },
    negative: { ttl: 30 },
    tags: (params, data) => data ? [`user:${params.id}`] : [],
  },
)

const redis = await loadService(redisService)
const cache = new RedisCache('app:', redis)
const userProfiles = await cache.loadCache(userProfileCache)

const profile = await userProfiles.read({ id: 'u1' })
await userProfiles.remove({ id: 'u1' })
await cache.removeTag('user:u1')
```

## Runtime And Lifecycle Notes

* `Cache(undefined)` removes the key unless negative caching is configured.
* `Cache#setExpire(seconds)` uses seconds.
* `defineCache` typed placeholders support `string`, `number`, and `boolean`.
* `RedisCache.loadCache()` returns `read`, `write`, `remove`, `has`, and `multi`.
* `RedisCache.removeTag(tag)` removes tagged cache entries.
* `fieldable` caches use Redis hashes and cannot combine with stale or negative cache options.
* `Scheduler.add()` supports cron strings and `{ delay }`.
* `Scheduler.load()` reads default exports from `*.schedule.*` files produced by `defineJob()`.
* `scanDirectory()` matches `.ts`, `.js`, `.tsx`, `.jsx`, and `.mjs`.

## Anti-Patterns

* Returning raw values from `defineCache` handlers instead of `new Cache(value)`.
* Treating cache as source of truth.
* Forgetting to destroy manually created Redis or TypeORM clients.
* Scheduling jobs without idempotency when side effects can repeat.
