Skip to content

Caching in Nexar

Tip

This is a bit of a more advanced topic, involving the actual under the hood API calls to Riot, which Nexar tries to hide from the user.

By and large, simply use the SMART_CACHE_CONFIG:

from nexar.client import NexarClient

client = NexarClient(
    riot_api_key="your_api_key",
)

This keeps a local, persistent storage of data to reduce API calls.

Nexar includes built-in caching functionality to reduce API calls and improve performance. Cached responses are either stored locally (sqlite file) or in memory, and reused until they expire.

Via CacheConfig, one can specify a default cache time, pick your storage backend, and configure endpoint TTLs (time-to-live's).

Quick Start

By default, Nexar uses "dumb" caching, which caches all responses for an hour to an SQLite file in ~/.nexar/, regardless of the endpoint:

import asyncio

from nexar.client import NexarClient
from nexar.enums import Region

client = NexarClient(
    riot_api_key="your_api_key",
    default_region=Region.NA1,
)


async def main() -> None:
    async with client:
        # First call hits the API
        player = await client.get_player("bexli", "bex")

        # Second call uses cached data
        player = await client.get_player("bexli", "bex")


if __name__ == "__main__":
    asyncio.run(main())

Cache Backends

Nexar supports two cache backends:

  • SQLite (default): Persistent cache stored in a file. Best for long-running applications, CLI tools, and frequent re-runs.
  • Memory: Ephemeral in-memory cache. Best for one-off analysis scripts, tests, and environments without write access (like AWS Lambda).

You can explicitly configure the backend using CacheConfig:

import asyncio
import os
from nexar.client import NexarClient
from nexar.cache import CacheConfig
from nexar.enums import Region


async def main():
    api_key = os.environ.get("RIOT_API_KEY")
    if not api_key:
        print("Please set RIOT_API_KEY environment variable.")
        return

    # 1. Custom SQLite Configuration
    # Useful for separating dev/prod caches or specific tool caches
    sqlite_config = CacheConfig(
        backend="sqlite",
        cache_name="my_custom_cache",  # Creates my_custom_cache.sqlite
        expire_after=3600,  # 1 hour default expiration
    )

    print("--- Using Custom SQLite Backend ---")
    async with NexarClient(riot_api_key=api_key, cache_config=sqlite_config) as client:
        # Note: Using get_player which returns a Player object with both account and summoner data
        player = await client.get_player("Agurin", "EUW", Region.EUW1)
        print(f"Got player (SQLite): {player.game_name}#{player.tag_line}")

    # 2. Memory Configuration
    # Useful for tests, scripts, or read-only environments (Lambda/Cloud Run)
    memory_config = CacheConfig(
        backend="memory",
        expire_after=600,  # 10 minutes default
    )

    print("\n--- Using Memory Backend ---")
    async with NexarClient(riot_api_key=api_key, cache_config=memory_config) as client:
        player = await client.get_player("Agurin", "EUW", Region.EUW1)
        print(f"Got player (Memory): {player.game_name}#{player.tag_line}")


if __name__ == "__main__":
    asyncio.run(main())

SQLite Cache Location

By default, the SQLite backend creates a file named nexar_cache.sqlite in ~/.nexar/. You can change the location or name:

config = CacheConfig(
    backend="sqlite",
    cache_name="my_app_cache",  # Creates my_app_cache.sqlite
    cache_dir="/tmp/cache"      # Saves to /tmp/cache/my_app_cache.sqlite
)

Note

For creating your own endpoint config, consult the Riot API docs

You can create your own cache configuration, and set things like the path to your database file or a custom endpoint durations, etc.

from nexar import CacheConfig

# SQLite cache with custom settings
custom_config = CacheConfig(
    backend="sqlite",
    cache_dir="/var/cache/nexar/",
    expire_after=7200,  # Default 2 hours
    endpoint_config={
        "/riot/account/v1/accounts/by-riot-id": {"expire_after": None},  # Never cache Riot ID
    },
)

# Memory cache with custom expiration
memory_config = CacheConfig(
    backend="memory",
    expire_after=900,  # 15 minutes
)

On, even easier, use the same endpoint config as the "smart" presets

from nexar.cache import SMART_CACHE_ENDPOINTS

# SQLite cache with custom settings
custom_config = CacheConfig(
    backend="sqlite",
    cache_dir="./my_cache",
    endpoint_config=SMART_CACHE_ENDPOINTS,
)

# Memory cache with custom expiration
memory_config = CacheConfig(
    backend="memory",
    endpoint_config=SMART_CACHE_ENDPOINTS,
)

Predefined Configurations

DEFAULT_CACHE_CONFIG

Uses SQLite backend with 1-hour expiration for all endpoints.

SMART_CACHE_CONFIG/SMART_CACHE_CONFIG_MEMORY

Intelligently caches different endpoint types for optimal durations:

  • Account/Summoner data: 24 hours (rarely changes)
  • Match data: Forever (matches are immutable)
  • League entries: 5 minutes (rankings change frequently)
  • Match IDs: 1 minute (new matches appear)

MEMORY_CACHE_CONFIG

Uses in-memory caching with 30-minute expiration.

NO_CACHE_CONFIG

Disables caching entirely - every request hits the API.

Cache Management

async with NexarClient(riot_api_key="your_api_key") as client:
    # Get cache information
    info = await client.get_cache_info()

    # Clear cached data
    await client.clear_cache()

    # View API call statistics
    client.print_api_call_summary()

Best Practices

  1. Use SMART_CACHE_CONFIG for most applications. It provides sensible defaults for different endpoint types.
  2. Use SQLite backend when you want data to persist between runs. This saves API calls and speeds up development.
  3. Use Memory backend for scripts where persistence isn't needed or where file system access is restricted (e.g., serverless functions).
  4. Customize expiration times based on how frequently your data changes. Static data (Items, Champions) rarely changes, while Match History changes often.
  5. Disable caching for specific endpoints that need real-time data using per-endpoint configuration.