Skip to content

Cache Managment

Asaf Zorea edited this page Jan 25, 2026 · 1 revision

Cache Management

Overview

FastAccess uses .fidx (FASTA Index) cache files to dramatically speed up reopening FASTA files. The index is built once and reused, providing 40x faster loading for large genomes.

Cache File Format

  • Extension: .fidx
  • Format: JSON
  • Location: Same directory as FASTA by default, or custom cache_dir
  • Size: Typically <1 MB even for human genome

Example:

genome.fa       → genome.fa.fidx
genome.fa.gz    → genome.fa.gz.fidx

See FIDX Format Specification for details.

Default Behavior

from fastaccess import FastaStore

# First time: builds index (~2 seconds for human genome)
fa = FastaStore("genome.fa")

# Subsequent times: loads from cache (~0.05 seconds)
fa = FastaStore("genome.fa")  # 40x faster!

Cache Invalidation

The cache is automatically invalidated when:

  1. FASTA file is modified - Modification time (mtime) is checked
  2. Cache file is corrupted - Invalid JSON or missing fields
  3. Cache file is missing - No .fidx file found

When invalidated, the index is automatically rebuilt and cache is updated.

# Modify FASTA
with open("genome.fa", "a") as f:
    f.write(">newseq\nACTG\n")

# Next open will detect change and rebuild
fa = FastaStore("genome.fa")  # Rebuilds index automatically

Custom Cache Directory

Use a custom directory when FASTA files are in read-only locations:

from fastaccess import FastaStore

# FASTA in read-only directory, cache in writable location
fa = FastaStore(
    "/readonly/data/genome.fa",
    cache_dir="/tmp/fasta_cache"
)

# Cache is saved to: /tmp/fasta_cache/genome.fa.fidx
print(fa.get_cache_path())

Use cases:

  • FASTA on read-only filesystem (network share, mounted volume)
  • FASTA in system directories without write permissions
  • Organizing cache files separately from data files

Disabling Cache

Disable caching to always rebuild the index:

fa = FastaStore("genome.fa", use_cache=False)

# Index is built but NOT saved to disk
# Slower on subsequent opens

When to disable:

  • FASTA file changes frequently
  • Testing/debugging
  • Temporary analysis where cache won't be reused

Cache Inspection

Check cache status:

from fastaccess import FastaStore

fa = FastaStore("genome.fa")

# Was loaded from cache?
if fa.is_cached():
    print("Loaded from cache (fast)")
else:
    print("Built new index (slower)")

# Does cache file exist?
if fa.cache_exists():
    print(f"Cache at: {fa.get_cache_path()}")
else:
    print("No cache file")

Manual Cache Management

Get Cache Path

cache_path = fa.get_cache_path()
print(cache_path)  # /path/to/genome.fa.fidx

Force Rebuild

# Force rebuild index and update cache
fa.rebuild_index()
print("Index rebuilt")

When to rebuild:

  • Cache might be corrupted but not detected
  • FASTA file was modified but mtime wasn't updated
  • Want to regenerate with newer version of library

Delete Cache

# Delete cache file
if fa.delete_cache():
    print("Cache deleted successfully")
else:
    print("Cache file didn't exist or couldn't be deleted")

Cache File Lifecycle

┌─────────────────────┐
│ Open FASTA file     │
└──────────┬──────────┘
           │
           ▼
    ┌──────────────┐
    │ Cache exists?├──────No─────┐
    └──────┬───────┘             │
           │Yes                  │
           ▼                     ▼
    ┌──────────────┐      ┌─────────────┐
    │ mtime match? ├─No─→ │ Build index │
    └──────┬───────┘      └──────┬──────┘
           │Yes                  │
           ▼                     ▼
    ┌──────────────┐      ┌─────────────┐
    │ Load cache   │      │ Save cache  │
    └──────────────┘      └─────────────┘

Multi-User Scenarios

Shared Read-Only FASTA

Users can share FASTA but have individual caches:

# User A
fa = FastaStore("/shared/genome.fa", cache_dir="/home/userA/.cache/fasta")

# User B
fa = FastaStore("/shared/genome.fa", cache_dir="/home/userB/.cache/fasta")

Shared Cache Directory

Multiple users can share a cache directory with proper permissions:

# Setup shared cache
mkdir -p /shared/cache/fasta
chmod 777 /shared/cache/fasta  # Or use proper group permissions

# All users point to shared cache
fa = FastaStore("/data/genome.fa", cache_dir="/shared/cache/fasta")

Performance Comparison

Genome Size Build Index Load from Cache Speedup
10 MB 70 ms 2 ms 35x
100 MB 200 ms 5 ms 40x
3 GB (human) 2.0 s 50 ms 40x

Cache File Size

Cache files are very small relative to FASTA size:

FASTA Size Cache Size Ratio
10 MB ~50 KB 0.5%
100 MB ~200 KB 0.2%
3 GB ~800 KB 0.025%

Storage space for cache is negligible.

Troubleshooting

Permission Errors

Problem: Can't write cache file

Solution: Use custom cache directory:

fa = FastaStore("genome.fa", cache_dir="/tmp/cache")

Stale Cache

Problem: Cache not updating after FASTA modification

Solution: Force rebuild:

fa.rebuild_index()

Or delete cache and reopen:

fa.delete_cache()
fa = FastaStore("genome.fa")

Corrupted Cache

Problem: Cache file is corrupted

Solution: FastAccess automatically detects and rebuilds. If not:

import os
os.remove("genome.fa.fidx")
fa = FastaStore("genome.fa")  # Will rebuild

Multiple Processes

Problem: Multiple processes accessing same FASTA simultaneously

Solution: Each process can safely create its own FastaStore instance. Cache loading is read-only and thread-safe. Cache writing uses atomic file operations.

# Safe in multiprocessing
from multiprocessing import Pool
from fastaccess import FastaStore

def worker(chr_name):
    fa = FastaStore("genome.fa")  # Each process loads cache
    return fa.get_length(chr_name)

with Pool(4) as p:
    results = p.map(worker, ["chr1", "chr2", "chr3", "chr4"])

Best Practices

  1. Use default caching - Unless you have a specific reason not to
  2. Share FASTA, separate caches - For multi-user environments
  3. Keep cache files - They're small and speed up access significantly
  4. Use custom cache_dir - For read-only FASTA locations
  5. Don't commit cache to git - Add *.fidx to .gitignore
  6. Monitor cache age - Rebuild if FASTA was modified outside filesystem

Cleaning Up Old Caches

Find and remove all cache files:

# Find all .fidx files
find /path/to/data -name "*.fidx"

# Delete all .fidx files (be careful!)
find /path/to/data -name "*.fidx" -delete

# Delete caches older than 30 days
find /path/to/data -name "*.fidx" -mtime +30 -delete

Python script to clean old caches:

import os
import time
from pathlib import Path

def clean_old_caches(directory, days=30):
    """Delete cache files older than specified days."""
    cutoff = time.time() - (days * 86400)

    for fidx in Path(directory).rglob("*.fidx"):
        if fidx.stat().st_mtime < cutoff:
            print(f"Deleting old cache: {fidx}")
            fidx.unlink()

clean_old_caches("/data/fasta", days=30)

See Also