reference-api-buddy 0.4.3__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/CHANGELOG.md +38 -0
  2. {reference_api_buddy-0.4.3/reference_api_buddy.egg-info → reference_api_buddy-0.5.0}/PKG-INFO +147 -6
  3. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/README.md +145 -4
  4. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/pyproject.toml +2 -2
  5. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/config.py +11 -1
  6. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/handler.py +179 -73
  7. reference_api_buddy-0.5.0/reference_api_buddy/core/inflight_tracker.py +121 -0
  8. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/proxy.py +9 -2
  9. reference_api_buddy-0.5.0/reference_api_buddy/throttling/manager.py +224 -0
  10. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0/reference_api_buddy.egg-info}/PKG-INFO +147 -6
  11. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy.egg-info/SOURCES.txt +1 -0
  12. reference_api_buddy-0.4.3/reference_api_buddy/throttling/manager.py +0 -120
  13. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/LICENSE +0 -0
  14. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/MANIFEST.in +0 -0
  15. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/__init__.py +0 -0
  16. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/cache/__init__.py +0 -0
  17. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/cache/engine.py +0 -0
  18. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/cli.py +0 -0
  19. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/__init__.py +0 -0
  20. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/admin_utils.py +0 -0
  21. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/server.py +0 -0
  22. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/core/ttl_manager.py +0 -0
  23. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/database/__init__.py +0 -0
  24. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/database/manager.py +0 -0
  25. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/database/models.py +0 -0
  26. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/monitoring/manager.py +0 -0
  27. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/security/__init__.py +0 -0
  28. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/security/manager.py +0 -0
  29. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/throttling/__init__.py +0 -0
  30. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/utils/__init__.py +0 -0
  31. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy/utils/logger.py +0 -0
  32. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy.egg-info/dependency_links.txt +0 -0
  33. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy.egg-info/entry_points.txt +0 -0
  34. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy.egg-info/requires.txt +0 -0
  35. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/reference_api_buddy.egg-info/top_level.txt +0 -0
  36. {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.0}/setup.cfg +0 -0
@@ -6,6 +6,44 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
 
9
+ ## [0.5.0] - 2025-10-20
10
+
11
+ ### Added
12
+ - **Fine-grained rate limiting**: Per-second and per-minute rate limits for domain-specific throttling
13
+ - Configure `max_requests_per_second` and `max_requests_per_minute` in domain mappings
14
+ - Automatic request throttling with configurable delay tolerance
15
+ - Multi-window priority system (second → minute → hour)
16
+ - Sliding window implementation for accurate rate limiting
17
+ - Backward compatible with existing hour-level throttling
18
+ - **Request deduplication**: Automatic coalescing of concurrent requests to the same resource
19
+ - `InFlightTracker` class for tracking in-flight upstream requests
20
+ - Thread-safe coordination using threading events
21
+ - Prevents duplicate upstream API calls during request bursts
22
+ - Error propagation and timeout handling for waiting requests
23
+ - Automatic cleanup of completed requests
24
+ - Statistics reporting via `get_stats()`
25
+ - Comprehensive test coverage with 8 new tests for request deduplication and 9 tests for rate limiting
26
+ - Configuration validation for new rate limiting parameters
27
+
28
+ ### Changed
29
+ - `ThrottleManager` now accepts `domain_mappings` parameter to extract per-minute/per-second limits
30
+ - `ThrottleManager` extends `ThrottleState` to track minute and second-level request windows
31
+ - Request handler flow modified to use `get_required_delay()` instead of `should_throttle()`
32
+ - Proxy now sleeps automatically to stay within rate limits rather than rejecting requests with 429
33
+ - Only returns 429 when required delay exceeds `progressive_max_delay` (default 300 seconds)
34
+ - Request handler wraps upstream forwarding with deduplication logic
35
+ - Updated existing tests to work with new `get_required_delay()` method
36
+
37
+ ### Fixed
38
+ - Prevents burst requests to upstream APIs when multiple clients request the same resource simultaneously
39
+ - Eliminates race conditions during concurrent cache misses for identical resources
40
+
41
+ ### Performance
42
+ - Significant reduction in duplicate upstream API calls during request bursts
43
+ - Faster response times for waiting requests (share result instead of making duplicate calls)
44
+ - Better upstream API utilization with automatic rate smoothing
45
+ - **Deduplicated requests do NOT count against rate limits** - only the first upstream request is rate-limited
46
+
9
47
  ## [0.4.3] - 2025-09-16
10
48
 
11
49
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: reference-api-buddy
3
- Version: 0.4.3
3
+ Version: 0.5.0
4
4
  Summary: HTTP caching proxy module for development environments with reference APIs
5
5
  Author-email: Reference API Buddy Team <tinkermonkey25@gmail.com>
6
6
  Maintainer-email: Reference API Buddy Team <tinkermonkey25@gmail.com>
@@ -31,7 +31,7 @@ Project-URL: Repository, https://github.com/tinkermonkey/reference-api-buddy
31
31
  Project-URL: Issues, https://github.com/tinkermonkey/reference-api-buddy/issues
32
32
  Project-URL: Changelog, https://github.com/tinkermonkey/reference-api-buddy/blob/main/CHANGELOG.md
33
33
  Keywords: proxy,caching,api,http,development,rate-limiting
34
- Classifier: Development Status :: 3 - Alpha
34
+ Classifier: Development Status :: 4 - Beta
35
35
  Classifier: Intended Audience :: Developers
36
36
  Classifier: License :: OSI Approved :: MIT License
37
37
  Classifier: Programming Language :: Python :: 3
@@ -75,14 +75,16 @@ Dynamic: license-file
75
75
 
76
76
  # Reference API Buddy
77
77
 
78
- A Python caching proxy module designed for reference APIs where the data is non-secure and not changing frequently (ConceptNet, DBpedia, Wikidata, etc). The proxy provides configurable caching, progressive throttling, and detailed metrics to reduce API costs and prevent rate limiting. It is designed to be run on the "client" device, either embedded in a python app or standalone, and to service only specific domains through url manipulation and typically `HTTP` to `HTTPS` (`http://127.0.0.1/conceptnet/query...` -> `https://api.conceptnet.io/query...`). The URL manipulation scheme allows you to not need an `HTTP` proxy at the application level, so most traffic from your app will not pass through API Buddy. The `HTTP` -> `HTTPS` leg obviously meaningfuly shifts the security footprint for these requests, but if you need caching, this can be a lesser evil as you don't need to a) write your own custom API clients if this is only used during the dev cycle and b) ignore certs for `HTTPS` traffic in your app. So while the `HTTPS` security for the traffic to the reference sources is compromised, it leaves the rest of the traffic in your app secure. If your upstream API is highly sensitive and you think someone might be monitoring traffic on your local device, this is not for you.
78
+ A Python caching proxy module designed for reference APIs where the data is non-secure and not changing frequently (ConceptNet, DBpedia, Wikidata, etc). The proxy provides configurable caching, progressive throttling, and detailed metrics to reduce API costs and prevent rate limiting. It is designed to be run on the "client" device, either embedded in a python app or standalone, and to service only specific domains through url manipulation and typically `HTTP` to `HTTPS` (`http://127.0.0.1/conceptnet/query...` -> `https://api.conceptnet.io/query...`). The URL manipulation scheme allows you to not need an `HTTP` proxy at the application level, so most traffic from your app will not pass through API Buddy. The `HTTP` -> `HTTPS` leg obviously meaningfuly shifts the security footprint for these requests, but if you need caching, this can be a lesser evil as you don't need to a) write your own custom API clients if this is only used during the dev cycle and b) ignore certs for `HTTPS` traffic in your app. So while the traffic to the reference sources is HTTP locally inside of your process, all traffic leaving your system is HTTPS and certificates are still vetted for your sources. If your upstream API is highly sensitive and you think someone might be monitoring traffic on your local device, this is not for you.
79
79
 
80
80
  Currently this doesn't function as a vanilla MITM proxy since none of the upstream sources of interest are `HTTP` and this was built specifically to avoid having to disable `HTTPS` cert validation. If you're looking for a MITM proxy, there are many out there.
81
81
 
82
82
  ## Features
83
83
 
84
84
  - **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
85
- - **Progressive Throttling**: Domain-specific rate limiting with exponential backoff (applied only to upstream requests)
85
+ - **Request Deduplication**: Automatic coalescing of concurrent requests for the same resource to prevent duplicate upstream calls
86
+ - **Fine-Grained Rate Limiting**: Per-second, per-minute, and per-hour rate limits with automatic request throttling (applied only to cache misses)
87
+ - **Progressive Throttling**: Domain-specific rate limiting with exponential backoff
86
88
  - **Proxy Security**: Optional secure key authentication to control proxy access
87
89
  - **Upstream Pass-through**: Transparent forwarding of API keys and authentication to upstream APIs
88
90
  - **Metrics Collection**: Detailed statistics on cache performance, request patterns, and throttling
@@ -344,11 +346,14 @@ config = {
344
346
  "domain_mappings": {
345
347
  "conceptnet": {
346
348
  "upstream": "https://api.conceptnet.io",
347
- "ttl_seconds": 3600 # 1 hour for frequently changing data
349
+ "ttl_seconds": 3600, # 1 hour for frequently changing data
350
+ "max_requests_per_minute": 60, # Optional: limit to 60 requests per minute
351
+ "max_requests_per_second": 10 # Optional: limit to 10 requests per second
348
352
  },
349
353
  "wikidata": {
350
354
  "upstream": "https://www.wikidata.org",
351
- "ttl_seconds": 86400 # 1 day for more stable data
355
+ "ttl_seconds": 86400, # 1 day for more stable data
356
+ "max_requests_per_minute": 30 # Optional: limit to 30 requests per minute
352
357
  }
353
358
  },
354
359
  "server": {
@@ -427,6 +432,142 @@ response4 = requests.get("http://localhost:8080/api/other") # ✗ 429 Throttled
427
432
  - **Better user experience** - Frequently requested data remains fast
428
433
  - **Cost optimization** - Reduces upstream API usage and associated costs
429
434
 
435
+ ### Request Deduplication
436
+
437
+ When multiple clients make concurrent requests for the same resource and the cache misses, the proxy automatically **deduplicates** these requests to prevent unnecessary duplicate calls to the upstream API.
438
+
439
+ #### How It Works
440
+
441
+ **Automatic Coalescing:**
442
+ - When a cache miss occurs, the proxy checks if another thread is already fetching that resource
443
+ - If yes, subsequent requests **wait** for the first request to complete
444
+ - Once the first request finishes, **all waiting requests** receive the same result
445
+ - The result is then cached for future requests
446
+
447
+ **Example Scenario:**
448
+
449
+ ```python
450
+ # Client A, B, and C all request the same resource simultaneously
451
+ # (e.g., from a burst of parallel requests in an LLM pipeline)
452
+
453
+ Client A → Cache miss → Starts fetching from upstream
454
+ Client B → Cache miss → Sees A is fetching, waits for A's result
455
+ Client C → Cache miss → Sees A is fetching, waits for A's result
456
+
457
+ # When A completes:
458
+ A finishes → Returns result to Client A
459
+ → Returns same result to Client B (deduplicated)
460
+ → Returns same result to Client C (deduplicated)
461
+ → Caches result for future requests
462
+
463
+ # Result: Only 1 upstream request instead of 3!
464
+ ```
465
+
466
+ #### Benefits
467
+
468
+ - **Reduces upstream load**: Prevents duplicate requests during bursts
469
+ - **Cost savings**: Fewer API calls = lower costs for paid APIs
470
+ - **Faster responses**: Waiting requests get results instantly (no upstream round-trip)
471
+ - **Automatic**: No configuration required, works out of the box
472
+
473
+ #### Error Handling
474
+
475
+ - If the first request fails, the error is propagated to all waiting requests
476
+ - If the first request times out, waiting requests receive a 504 Gateway Timeout
477
+ - Default wait timeout is 60 seconds (configurable per request)
478
+
479
+ **Note**: Deduplication is based on the cache key (URL + method + body), so requests with different parameters are handled independently.
480
+
481
+ ---
482
+
483
+ ### Fine-Grained Rate Limiting
484
+
485
+ In addition to the hour-level throttling (configured via `throttling.domain_limits`), you can configure per-minute and per-second rate limits for individual domains. This is useful for APIs with strict rate limits or when you want to avoid bursting requests.
486
+
487
+ #### Configuration
488
+
489
+ Rate limits are configured per-domain in `domain_mappings`:
490
+
491
+ ```python
492
+ config = {
493
+ "domain_mappings": {
494
+ "wikidata": {
495
+ "upstream": "https://www.wikidata.org",
496
+ "max_requests_per_minute": 60, # Limit to 60 requests per minute
497
+ "max_requests_per_second": 10 # Limit to 10 requests per second
498
+ },
499
+ "openai": {
500
+ "upstream": "https://api.openai.com",
501
+ "max_requests_per_minute": 500 # Only per-minute limit
502
+ }
503
+ },
504
+ "throttling": {
505
+ "default_requests_per_hour": 1000, # Hour-level limit (all domains)
506
+ "progressive_max_delay": 300, # Max time to wait before returning 429
507
+ "domain_limits": {
508
+ "wikidata": 3000 # Hour-level limit for wikidata specifically
509
+ }
510
+ }
511
+ }
512
+ ```
513
+
514
+ #### How It Works
515
+
516
+ **Automatic Request Throttling:**
517
+ - When a cache miss occurs, the system calculates the required delay to stay within ALL configured rate limits (per-second, per-minute, and per-hour)
518
+ - If a delay is needed, the proxy **automatically sleeps** for that duration before making the upstream request
519
+ - The request eventually succeeds (no 429 error returned to client)
520
+
521
+ **Maximum Delay Protection:**
522
+ - If the required delay exceeds `progressive_max_delay` (default 300 seconds), the proxy returns `429 Too Many Requests` instead of waiting
523
+ - This prevents requests from blocking for excessive periods
524
+
525
+ **Multi-Window Priority:**
526
+ - The system checks all configured time windows and uses the **maximum delay** required across all windows
527
+ - Example: If per-second limit needs 0.5s delay and per-minute limit needs 5s delay, the proxy waits 5 seconds
528
+
529
+ **Example Flow:**
530
+
531
+ ```python
532
+ # With max_requests_per_second: 2 configured
533
+ proxy.start(blocking=False)
534
+
535
+ # Request 1 - No delay, immediate
536
+ response1 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
537
+
538
+ # Request 2 - No delay, immediate
539
+ response2 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
540
+
541
+ # Request 3 - Automatic delay before upstream request
542
+ response3 = requests.get("http://localhost:8080/wikidata/query?...") # Waits ~1 second, then completes
543
+
544
+ # Cache hits are NEVER delayed
545
+ cached = requests.get("http://localhost:8080/wikidata/query?...") # Instant (cache hit)
546
+ ```
547
+
548
+ #### Use Cases
549
+
550
+ **Per-Second Limits:**
551
+ - Prevent request bursts
552
+ - Smooth out traffic to upstream APIs
553
+ - Comply with strict burst rate limits
554
+
555
+ **Per-Minute Limits:**
556
+ - Control sustained request rates
557
+ - Stay within API tier limits (e.g., "60 requests per minute")
558
+ - Avoid triggering upstream rate limiters
559
+
560
+ **Combined Limits:**
561
+ - Enforce both burst protection (per-second) and sustained rate control (per-minute/hour)
562
+ - Example: "Max 10 req/sec, 300 req/min, 5000 req/hour"
563
+
564
+ #### Configuration Notes
565
+
566
+ - All rate limit parameters are **optional**
567
+ - Rate limits apply **only to cache misses** (cache hits bypass all throttling)
568
+ - Parameters only need to be specified for domains that require rate limiting
569
+ - If not specified, only the hour-level throttling applies (via `throttling.domain_limits`)
570
+
430
571
  ### TTL (Time To Live) Configuration
431
572
 
432
573
  The proxy supports flexible TTL configuration at both system-wide and per-domain levels:
@@ -1,13 +1,15 @@
1
1
  # Reference API Buddy
2
2
 
3
- A Python caching proxy module designed for reference APIs where the data is non-secure and not changing frequently (ConceptNet, DBpedia, Wikidata, etc). The proxy provides configurable caching, progressive throttling, and detailed metrics to reduce API costs and prevent rate limiting. It is designed to be run on the "client" device, either embedded in a python app or standalone, and to service only specific domains through url manipulation and typically `HTTP` to `HTTPS` (`http://127.0.0.1/conceptnet/query...` -> `https://api.conceptnet.io/query...`). The URL manipulation scheme allows you to not need an `HTTP` proxy at the application level, so most traffic from your app will not pass through API Buddy. The `HTTP` -> `HTTPS` leg obviously meaningfuly shifts the security footprint for these requests, but if you need caching, this can be a lesser evil as you don't need to a) write your own custom API clients if this is only used during the dev cycle and b) ignore certs for `HTTPS` traffic in your app. So while the `HTTPS` security for the traffic to the reference sources is compromised, it leaves the rest of the traffic in your app secure. If your upstream API is highly sensitive and you think someone might be monitoring traffic on your local device, this is not for you.
3
+ A Python caching proxy module designed for reference APIs where the data is non-secure and not changing frequently (ConceptNet, DBpedia, Wikidata, etc). The proxy provides configurable caching, progressive throttling, and detailed metrics to reduce API costs and prevent rate limiting. It is designed to be run on the "client" device, either embedded in a python app or standalone, and to service only specific domains through url manipulation and typically `HTTP` to `HTTPS` (`http://127.0.0.1/conceptnet/query...` -> `https://api.conceptnet.io/query...`). The URL manipulation scheme allows you to not need an `HTTP` proxy at the application level, so most traffic from your app will not pass through API Buddy. The `HTTP` -> `HTTPS` leg obviously meaningfuly shifts the security footprint for these requests, but if you need caching, this can be a lesser evil as you don't need to a) write your own custom API clients if this is only used during the dev cycle and b) ignore certs for `HTTPS` traffic in your app. So while the traffic to the reference sources is HTTP locally inside of your process, all traffic leaving your system is HTTPS and certificates are still vetted for your sources. If your upstream API is highly sensitive and you think someone might be monitoring traffic on your local device, this is not for you.
4
4
 
5
5
  Currently this doesn't function as a vanilla MITM proxy since none of the upstream sources of interest are `HTTP` and this was built specifically to avoid having to disable `HTTPS` cert validation. If you're looking for a MITM proxy, there are many out there.
6
6
 
7
7
  ## Features
8
8
 
9
9
  - **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
10
- - **Progressive Throttling**: Domain-specific rate limiting with exponential backoff (applied only to upstream requests)
10
+ - **Request Deduplication**: Automatic coalescing of concurrent requests for the same resource to prevent duplicate upstream calls
11
+ - **Fine-Grained Rate Limiting**: Per-second, per-minute, and per-hour rate limits with automatic request throttling (applied only to cache misses)
12
+ - **Progressive Throttling**: Domain-specific rate limiting with exponential backoff
11
13
  - **Proxy Security**: Optional secure key authentication to control proxy access
12
14
  - **Upstream Pass-through**: Transparent forwarding of API keys and authentication to upstream APIs
13
15
  - **Metrics Collection**: Detailed statistics on cache performance, request patterns, and throttling
@@ -269,11 +271,14 @@ config = {
269
271
  "domain_mappings": {
270
272
  "conceptnet": {
271
273
  "upstream": "https://api.conceptnet.io",
272
- "ttl_seconds": 3600 # 1 hour for frequently changing data
274
+ "ttl_seconds": 3600, # 1 hour for frequently changing data
275
+ "max_requests_per_minute": 60, # Optional: limit to 60 requests per minute
276
+ "max_requests_per_second": 10 # Optional: limit to 10 requests per second
273
277
  },
274
278
  "wikidata": {
275
279
  "upstream": "https://www.wikidata.org",
276
- "ttl_seconds": 86400 # 1 day for more stable data
280
+ "ttl_seconds": 86400, # 1 day for more stable data
281
+ "max_requests_per_minute": 30 # Optional: limit to 30 requests per minute
277
282
  }
278
283
  },
279
284
  "server": {
@@ -352,6 +357,142 @@ response4 = requests.get("http://localhost:8080/api/other") # ✗ 429 Throttled
352
357
  - **Better user experience** - Frequently requested data remains fast
353
358
  - **Cost optimization** - Reduces upstream API usage and associated costs
354
359
 
360
+ ### Request Deduplication
361
+
362
+ When multiple clients make concurrent requests for the same resource and the cache misses, the proxy automatically **deduplicates** these requests to prevent unnecessary duplicate calls to the upstream API.
363
+
364
+ #### How It Works
365
+
366
+ **Automatic Coalescing:**
367
+ - When a cache miss occurs, the proxy checks if another thread is already fetching that resource
368
+ - If yes, subsequent requests **wait** for the first request to complete
369
+ - Once the first request finishes, **all waiting requests** receive the same result
370
+ - The result is then cached for future requests
371
+
372
+ **Example Scenario:**
373
+
374
+ ```python
375
+ # Client A, B, and C all request the same resource simultaneously
376
+ # (e.g., from a burst of parallel requests in an LLM pipeline)
377
+
378
+ Client A → Cache miss → Starts fetching from upstream
379
+ Client B → Cache miss → Sees A is fetching, waits for A's result
380
+ Client C → Cache miss → Sees A is fetching, waits for A's result
381
+
382
+ # When A completes:
383
+ A finishes → Returns result to Client A
384
+ → Returns same result to Client B (deduplicated)
385
+ → Returns same result to Client C (deduplicated)
386
+ → Caches result for future requests
387
+
388
+ # Result: Only 1 upstream request instead of 3!
389
+ ```
390
+
391
+ #### Benefits
392
+
393
+ - **Reduces upstream load**: Prevents duplicate requests during bursts
394
+ - **Cost savings**: Fewer API calls = lower costs for paid APIs
395
+ - **Faster responses**: Waiting requests get results instantly (no upstream round-trip)
396
+ - **Automatic**: No configuration required, works out of the box
397
+
398
+ #### Error Handling
399
+
400
+ - If the first request fails, the error is propagated to all waiting requests
401
+ - If the first request times out, waiting requests receive a 504 Gateway Timeout
402
+ - Default wait timeout is 60 seconds (configurable per request)
403
+
404
+ **Note**: Deduplication is based on the cache key (URL + method + body), so requests with different parameters are handled independently.
405
+
406
+ ---
407
+
408
+ ### Fine-Grained Rate Limiting
409
+
410
+ In addition to the hour-level throttling (configured via `throttling.domain_limits`), you can configure per-minute and per-second rate limits for individual domains. This is useful for APIs with strict rate limits or when you want to avoid bursting requests.
411
+
412
+ #### Configuration
413
+
414
+ Rate limits are configured per-domain in `domain_mappings`:
415
+
416
+ ```python
417
+ config = {
418
+ "domain_mappings": {
419
+ "wikidata": {
420
+ "upstream": "https://www.wikidata.org",
421
+ "max_requests_per_minute": 60, # Limit to 60 requests per minute
422
+ "max_requests_per_second": 10 # Limit to 10 requests per second
423
+ },
424
+ "openai": {
425
+ "upstream": "https://api.openai.com",
426
+ "max_requests_per_minute": 500 # Only per-minute limit
427
+ }
428
+ },
429
+ "throttling": {
430
+ "default_requests_per_hour": 1000, # Hour-level limit (all domains)
431
+ "progressive_max_delay": 300, # Max time to wait before returning 429
432
+ "domain_limits": {
433
+ "wikidata": 3000 # Hour-level limit for wikidata specifically
434
+ }
435
+ }
436
+ }
437
+ ```
438
+
439
+ #### How It Works
440
+
441
+ **Automatic Request Throttling:**
442
+ - When a cache miss occurs, the system calculates the required delay to stay within ALL configured rate limits (per-second, per-minute, and per-hour)
443
+ - If a delay is needed, the proxy **automatically sleeps** for that duration before making the upstream request
444
+ - The request eventually succeeds (no 429 error returned to client)
445
+
446
+ **Maximum Delay Protection:**
447
+ - If the required delay exceeds `progressive_max_delay` (default 300 seconds), the proxy returns `429 Too Many Requests` instead of waiting
448
+ - This prevents requests from blocking for excessive periods
449
+
450
+ **Multi-Window Priority:**
451
+ - The system checks all configured time windows and uses the **maximum delay** required across all windows
452
+ - Example: If per-second limit needs 0.5s delay and per-minute limit needs 5s delay, the proxy waits 5 seconds
453
+
454
+ **Example Flow:**
455
+
456
+ ```python
457
+ # With max_requests_per_second: 2 configured
458
+ proxy.start(blocking=False)
459
+
460
+ # Request 1 - No delay, immediate
461
+ response1 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
462
+
463
+ # Request 2 - No delay, immediate
464
+ response2 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
465
+
466
+ # Request 3 - Automatic delay before upstream request
467
+ response3 = requests.get("http://localhost:8080/wikidata/query?...") # Waits ~1 second, then completes
468
+
469
+ # Cache hits are NEVER delayed
470
+ cached = requests.get("http://localhost:8080/wikidata/query?...") # Instant (cache hit)
471
+ ```
472
+
473
+ #### Use Cases
474
+
475
+ **Per-Second Limits:**
476
+ - Prevent request bursts
477
+ - Smooth out traffic to upstream APIs
478
+ - Comply with strict burst rate limits
479
+
480
+ **Per-Minute Limits:**
481
+ - Control sustained request rates
482
+ - Stay within API tier limits (e.g., "60 requests per minute")
483
+ - Avoid triggering upstream rate limiters
484
+
485
+ **Combined Limits:**
486
+ - Enforce both burst protection (per-second) and sustained rate control (per-minute/hour)
487
+ - Example: "Max 10 req/sec, 300 req/min, 5000 req/hour"
488
+
489
+ #### Configuration Notes
490
+
491
+ - All rate limit parameters are **optional**
492
+ - Rate limits apply **only to cache misses** (cache hits bypass all throttling)
493
+ - Parameters only need to be specified for domains that require rate limiting
494
+ - If not specified, only the hour-level throttling applies (via `throttling.domain_limits`)
495
+
355
496
  ### TTL (Time To Live) Configuration
356
497
 
357
498
  The proxy supports flexible TTL configuration at both system-wide and per-domain levels:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "reference-api-buddy"
7
- version = "0.4.3"
7
+ version = "0.5.0"
8
8
  description = "HTTP caching proxy module for development environments with reference APIs"
9
9
  readme = "README.md"
10
10
  license = {file = "LICENSE"}
@@ -15,7 +15,7 @@ maintainers = [
15
15
  {name = "Reference API Buddy Team", email = "tinkermonkey25@gmail.com"}
16
16
  ]
17
17
  classifiers = [
18
- "Development Status :: 3 - Alpha",
18
+ "Development Status :: 4 - Beta",
19
19
  "Intended Audience :: Developers",
20
20
  "License :: OSI Approved :: MIT License",
21
21
  "Programming Language :: Python :: 3",
@@ -107,7 +107,7 @@ class ConfigurationValidator:
107
107
  if not isinstance(logging_cfg.get("backup_count", None), int):
108
108
  errors.append("logging.backup_count must be an integer.")
109
109
 
110
- # Validate domain-specific TTL
110
+ # Validate domain-specific TTL and rate limits
111
111
  domain_mappings = config.get("domain_mappings", {})
112
112
  for domain_key, mapping in domain_mappings.items():
113
113
  if isinstance(mapping, dict):
@@ -115,6 +115,16 @@ class ConfigurationValidator:
115
115
  if ttl is not None and (not isinstance(ttl, int) or ttl <= 0):
116
116
  errors.append(f"domain_mappings.{domain_key}.ttl_seconds must be a positive integer.")
117
117
 
118
+ # Validate max_requests_per_minute
119
+ rpm = mapping.get("max_requests_per_minute")
120
+ if rpm is not None and (not isinstance(rpm, int) or rpm <= 0):
121
+ errors.append(f"domain_mappings.{domain_key}.max_requests_per_minute must be a positive integer.")
122
+
123
+ # Validate max_requests_per_second
124
+ rps = mapping.get("max_requests_per_second")
125
+ if rps is not None and (not isinstance(rps, int) or rps <= 0):
126
+ errors.append(f"domain_mappings.{domain_key}.max_requests_per_second must be a positive integer.")
127
+
118
128
  # Validate admin configuration
119
129
  admin = config.get("admin", {})
120
130
  if not isinstance(admin.get("enabled", None), bool):