redis_backend
Redis-based distributed cache backend for PRIMARY mode.
This backend wraps a file-based backend and adds distributed caching via Redis. It's designed for PRIMARY mode multi-worker deployments where multiple FastAPI workers need to share cached model reference data.
RedisBackend
Bases: ModelReferenceBackend
Redis-backed distributed cache with file backend fallback.
Architecture: - File backend is the source of truth - Redis provides distributed caching across multiple PRIMARY workers - On cache miss, reads from file backend and populates Redis - Pub/sub notifies other workers of cache invalidations - Only usable in PRIMARY mode
Source code in src/horde_model_reference/backends/redis_backend.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 | |
_invalidation_callbacks
instance-attribute
__init__
__init__(
*,
file_backend: FileSystemBackend,
redis_settings: RedisSettings,
cache_ttl_seconds: int | None = None,
) -> None
Initialize Redis backend with filesystem backend.
Parameters:
-
file_backend(FileSystemBackend) –Filesystem backend to wrap.
-
redis_settings(RedisSettings) –Redis connection settings.
-
cache_ttl_seconds(int | None, default:None) –TTL for cache entries. If None, uses redis_settings.ttl_seconds.
Raises:
-
ValueError–If file_backend is not in PRIMARY mode.
Source code in src/horde_model_reference/backends/redis_backend.py
_create_sync_pool
Create synchronous Redis connection pool.
Source code in src/horde_model_reference/backends/redis_backend.py
_category_key
_legacy_metadata_key
Generate Redis key for legacy metadata.
_v2_metadata_key
_invalidation_channel
_setup_pubsub
Set up pub/sub for cache invalidation events.
Source code in src/horde_model_reference/backends/redis_backend.py
_listen_for_invalidations
Listen for cache invalidation events from other workers.
Source code in src/horde_model_reference/backends/redis_backend.py
_retry_redis_operation
_retry_redis_operation(
operation: Callable[
..., str | bool | bytes | int | None
],
*args: str | int | float | None,
**kwargs: str | int | float | None,
) -> str | bool | int | bytes | None
Retry a Redis operation with full-jitter exponential backoff.
Source code in src/horde_model_reference/backends/redis_backend.py
fetch_category
fetch_category(
category: MODEL_REFERENCE_CATEGORY,
*,
force_refresh: bool = False,
) -> dict[str, Any] | None
Fetch from Redis cache, fallback to file backend on miss.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to fetch.
-
force_refresh(bool, default:False) –If True, bypass Redis cache and fetch from files.
Returns:
Source code in src/horde_model_reference/backends/redis_backend.py
fetch_all_categories
fetch_all_categories(
*, force_refresh: bool = False
) -> dict[MODEL_REFERENCE_CATEGORY, dict[str, Any] | None]
Fetch all categories, using Redis cache where available.
Source code in src/horde_model_reference/backends/redis_backend.py
fetch_category_async
async
fetch_category_async(
category: MODEL_REFERENCE_CATEGORY,
*,
httpx_client: AsyncClient | None = None,
force_refresh: bool = False,
) -> dict[str, Any] | None
Asynchronously fetch from Redis, fallback to file backend.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to fetch.
-
httpx_client(AsyncClient | None, default:None) –Optional shared HTTPX client for file backend.
-
force_refresh(bool, default:False) –If True, bypass Redis cache.
Returns:
Source code in src/horde_model_reference/backends/redis_backend.py
fetch_all_categories_async
async
fetch_all_categories_async(
*,
httpx_client: AsyncClient | None = None,
force_refresh: bool = False,
) -> dict[MODEL_REFERENCE_CATEGORY, dict[str, Any] | None]
Asynchronously fetch all categories from Redis with PRIMARY API fallback.
Source code in src/horde_model_reference/backends/redis_backend.py
needs_refresh
Check if category needs refresh (delegates to file backend).
_mark_stale_impl
Mark category as stale and invalidate Redis cache.
Also publishes invalidation event to notify other workers.
Source code in src/horde_model_reference/backends/redis_backend.py
get_category_file_path
Get file path (delegates to file backend).
get_all_category_file_paths
Get all file paths (delegates to file backend).
get_legacy_json
get_legacy_json(
category: MODEL_REFERENCE_CATEGORY,
redownload: bool = False,
) -> dict[str, Any] | None
Get legacy JSON (delegates to file backend).
Source code in src/horde_model_reference/backends/redis_backend.py
get_legacy_json_string
get_legacy_json_string(
category: MODEL_REFERENCE_CATEGORY,
redownload: bool = False,
) -> str | None
Get legacy JSON string (delegates to file backend).
Source code in src/horde_model_reference/backends/redis_backend.py
get_replicate_mode
supports_writes
Check if backend supports writes (delegates to file backend).
supports_metadata
Check if backend supports metadata tracking (delegates to file backend).
Returns:
-
bool(bool) –True if file backend supports metadata.
Source code in src/horde_model_reference/backends/redis_backend.py
supports_cache_warming
supports_health_checks
supports_statistics
update_model
update_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_dict: dict[str, Any],
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update model via file backend, then invalidate Redis cache.
Source code in src/horde_model_reference/backends/redis_backend.py
delete_model
delete_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Delete model via file backend, then invalidate Redis cache.
Source code in src/horde_model_reference/backends/redis_backend.py
warm_cache
Pre-populate Redis cache from files on startup.
Source code in src/horde_model_reference/backends/redis_backend.py
warm_cache_async
async
Asynchronously pre-populate Redis cache.
Source code in src/horde_model_reference/backends/redis_backend.py
health_check
Check Redis connectivity.
Source code in src/horde_model_reference/backends/redis_backend.py
get_statistics
Get Redis cache statistics.
Returns:
-
dict[str, Any]–dict containing: - connected: Whether Redis is connected - keys_count: Number of keys in Redis database - total_connections: Total connections received - total_commands: Total commands processed - memory_used_bytes: Memory used in bytes - memory_used_human: Human-readable memory usage
Source code in src/horde_model_reference/backends/redis_backend.py
get_legacy_metadata
Get legacy format metadata, using Redis cache.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata–CategoryMetadata | None: The legacy metadata, or None if not available.
Source code in src/horde_model_reference/backends/redis_backend.py
get_legacy_metadata_async
async
Asynchronously get legacy format metadata, using Redis cache.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata–CategoryMetadata | None: The legacy metadata, or None if not available.
Source code in src/horde_model_reference/backends/redis_backend.py
get_metadata
Get v2 format metadata, using Redis cache.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata–CategoryMetadata | None: The v2 metadata, or None if not available.
Source code in src/horde_model_reference/backends/redis_backend.py
get_metadata_async
async
Asynchronously get v2 format metadata, using Redis cache.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to get metadata for.
Returns:
-
CategoryMetadata–CategoryMetadata | None: The v2 metadata, or None if not available.
Source code in src/horde_model_reference/backends/redis_backend.py
get_all_legacy_metadata
Get legacy format metadata for all categories.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their legacy metadata.
Source code in src/horde_model_reference/backends/redis_backend.py
get_all_legacy_metadata_async
async
Asynchronously get legacy format metadata for all categories.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their legacy metadata.
Source code in src/horde_model_reference/backends/redis_backend.py
get_all_metadata
Get v2 format metadata for all categories.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their v2 metadata.
Source code in src/horde_model_reference/backends/redis_backend.py
get_all_metadata_async
async
Asynchronously get v2 format metadata for all categories.
Returns:
-
dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]–dict[MODEL_REFERENCE_CATEGORY, CategoryMetadata]: Mapping of categories to their v2 metadata.
Source code in src/horde_model_reference/backends/redis_backend.py
__del__
Clean up Redis connections on deletion.
Source code in src/horde_model_reference/backends/redis_backend.py
register_invalidation_callback
Register a callback to be called when a category is invalidated.
This allows external components (like ModelReferenceManager) to be notified when cached data becomes stale and needs to be refreshed.
Parameters:
-
callback(Callable[[MODEL_REFERENCE_CATEGORY], None]) –Function to call with the invalidated category.
Source code in src/horde_model_reference/backends/base.py
_notify_invalidation
Notify all registered callbacks that a category has been invalidated.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category that was invalidated.
Source code in src/horde_model_reference/backends/base.py
mark_stale
Mark a category's data as stale, requiring refresh on next access.
This method calls the backend-specific implementation and then notifies all registered callbacks.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to mark as stale.
Implementation Note
The base class provides this public implementation. Subclasses should override _mark_stale_impl() instead of this method.
See Also
- _mark_stale_impl(): Backend-specific staleness tracking
- register_invalidation_callback(): Register callbacks for invalidation events
Source code in src/horde_model_reference/backends/base.py
support_any_writes
Check if this backend supports any write operations (v2 or legacy).
Returns:
-
bool(bool) –True if any write operations are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
supports_legacy_writes
Check if this backend supports write operations in legacy format.
Legacy write operations include update_model_legacy() and delete_model_legacy(). Only available when canonical_format='LEGACY' in PRIMARY mode.
Returns:
-
bool(bool) –True if legacy write operations are supported, False otherwise.
Source code in src/horde_model_reference/backends/base.py
update_model_from_base_model
update_model_from_base_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_model: BaseModel,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference from a pydantic BaseModel.
This is an optional method that write-capable backends can implement. Read-only backends should leave the default implementation which raises NotImplementedError.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_model(BaseModel) –The model record data as a pydantic BaseModel.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support write operations.
Implementation Note
The base class provides this implementation automatically. It:
1. Checks supports_writes() returns True
2. Converts the pydantic model to dict using model_dump(exclude_unset=True)
3. Calls update_model() with the dictionary
Backends that support writes typically don't need to override this method.
See Also
- update_model(): Update from dictionary (implement this)
- supports_writes(): Feature detection method
Source code in src/horde_model_reference/backends/base.py
update_model_legacy
update_model_legacy(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_dict: dict[str, Any],
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference in legacy format.
This is an optional method that legacy-write-capable backends can implement. Only available when canonical_format='LEGACY' in PRIMARY mode.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_dict(dict[str, Any]) –The model record data in legacy format as a dictionary.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support legacy write operations.
Source code in src/horde_model_reference/backends/base.py
update_model_legacy_from_base_model
update_model_legacy_from_base_model(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
record_model: BaseModel,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Update or create a model reference in legacy format from a pydantic BaseModel.
This is an optional method that legacy-write-capable backends can implement. Only available when canonical_format='LEGACY' in PRIMARY mode.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category to update.
-
model_name(str) –The name of the model to update or create.
-
record_model(BaseModel) –The model record data as a pydantic BaseModel.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support legacy write operations.
Source code in src/horde_model_reference/backends/base.py
delete_model_legacy
delete_model_legacy(
category: MODEL_REFERENCE_CATEGORY,
model_name: str,
*,
logical_user_id: str | None = None,
request_id: str | None = None,
) -> None
Delete a model reference from legacy format files.
This is an optional method that legacy-write-capable backends can implement. Only available when canonical_format='LEGACY' in PRIMARY mode.
Parameters:
-
category(MODEL_REFERENCE_CATEGORY) –The category containing the model.
-
model_name(str) –The name of the model to delete.
-
logical_user_id(str | None, default:None) –Immutable Horde user id for auditing contexts (optional).
-
request_id(str | None, default:None) –Optional tracing/idempotency identifier for audit correlation.
Raises:
-
NotImplementedError–If the backend does not support legacy write operations.