reference-api-buddy 0.4.3__tar.gz → 0.5.1__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.
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/CHANGELOG.md +58 -0
- {reference_api_buddy-0.4.3/reference_api_buddy.egg-info → reference_api_buddy-0.5.1}/PKG-INFO +153 -6
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/README.md +151 -4
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/pyproject.toml +2 -2
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/__init__.py +1 -1
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/config.py +17 -1
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/handler.py +243 -143
- reference_api_buddy-0.5.1/reference_api_buddy/core/inflight_tracker.py +121 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/proxy.py +11 -2
- reference_api_buddy-0.5.1/reference_api_buddy/throttling/manager.py +224 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1/reference_api_buddy.egg-info}/PKG-INFO +153 -6
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/SOURCES.txt +1 -0
- reference_api_buddy-0.4.3/reference_api_buddy/throttling/manager.py +0 -120
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/LICENSE +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/MANIFEST.in +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/cache/__init__.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/cache/engine.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/cli.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/__init__.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/admin_utils.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/server.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/core/ttl_manager.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/database/__init__.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/database/manager.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/database/models.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/monitoring/manager.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/security/__init__.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/security/manager.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/throttling/__init__.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/utils/__init__.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy/utils/logger.py +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/dependency_links.txt +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/entry_points.txt +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/requires.txt +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/reference_api_buddy.egg-info/top_level.txt +0 -0
- {reference_api_buddy-0.4.3 → reference_api_buddy-0.5.1}/setup.cfg +0 -0
|
@@ -6,6 +6,64 @@ 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.1] - 2026-11-24
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- **Upstream errors are no longer cached.** Only 2xx responses are stored, so an outage or a 4xx no longer
|
|
13
|
+
blanks a resource for the whole TTL. Throttled (429) responses are not cached either.
|
|
14
|
+
- **Upstream HTTP error statuses are passed through.** A 404 or 503 from upstream now reaches the caller with its
|
|
15
|
+
real status, body and headers instead of a generic 502. Network errors and unmapped upstreams still return 502.
|
|
16
|
+
- **A request answered with a 429 no longer stays in-flight forever.** The request that owns an in-flight entry now
|
|
17
|
+
releases it on every path, so later requests for the same resource get a prompt 429 instead of waiting 60s and
|
|
18
|
+
failing with a 500.
|
|
19
|
+
- **PUT and DELETE requests no longer share an in-flight slot.** They have no cache key and previously all
|
|
20
|
+
deduplicated onto the same entry, so concurrent requests could receive each other's responses.
|
|
21
|
+
- **`cache.max_cache_entries` is read from config.** The cache was capped at 1,000 entries whatever the config said.
|
|
22
|
+
The default stays 1,000; the value must be a positive integer.
|
|
23
|
+
- `reference_api_buddy.__version__` now matches the package version.
|
|
24
|
+
|
|
25
|
+
### Tests
|
|
26
|
+
- Regression tests for all of the above against a local upstream server.
|
|
27
|
+
- Expiry tests no longer use a hard-coded "far future" timestamp that has since passed.
|
|
28
|
+
|
|
29
|
+
## [0.5.0] - 2025-10-20
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
- **Fine-grained rate limiting**: Per-second and per-minute rate limits for domain-specific throttling
|
|
33
|
+
- Configure `max_requests_per_second` and `max_requests_per_minute` in domain mappings
|
|
34
|
+
- Automatic request throttling with configurable delay tolerance
|
|
35
|
+
- Multi-window priority system (second → minute → hour)
|
|
36
|
+
- Sliding window implementation for accurate rate limiting
|
|
37
|
+
- Backward compatible with existing hour-level throttling
|
|
38
|
+
- **Request deduplication**: Automatic coalescing of concurrent requests to the same resource
|
|
39
|
+
- `InFlightTracker` class for tracking in-flight upstream requests
|
|
40
|
+
- Thread-safe coordination using threading events
|
|
41
|
+
- Prevents duplicate upstream API calls during request bursts
|
|
42
|
+
- Error propagation and timeout handling for waiting requests
|
|
43
|
+
- Automatic cleanup of completed requests
|
|
44
|
+
- Statistics reporting via `get_stats()`
|
|
45
|
+
- Comprehensive test coverage with 8 new tests for request deduplication and 9 tests for rate limiting
|
|
46
|
+
- Configuration validation for new rate limiting parameters
|
|
47
|
+
|
|
48
|
+
### Changed
|
|
49
|
+
- `ThrottleManager` now accepts `domain_mappings` parameter to extract per-minute/per-second limits
|
|
50
|
+
- `ThrottleManager` extends `ThrottleState` to track minute and second-level request windows
|
|
51
|
+
- Request handler flow modified to use `get_required_delay()` instead of `should_throttle()`
|
|
52
|
+
- Proxy now sleeps automatically to stay within rate limits rather than rejecting requests with 429
|
|
53
|
+
- Only returns 429 when required delay exceeds `progressive_max_delay` (default 300 seconds)
|
|
54
|
+
- Request handler wraps upstream forwarding with deduplication logic
|
|
55
|
+
- Updated existing tests to work with new `get_required_delay()` method
|
|
56
|
+
|
|
57
|
+
### Fixed
|
|
58
|
+
- Prevents burst requests to upstream APIs when multiple clients request the same resource simultaneously
|
|
59
|
+
- Eliminates race conditions during concurrent cache misses for identical resources
|
|
60
|
+
|
|
61
|
+
### Performance
|
|
62
|
+
- Significant reduction in duplicate upstream API calls during request bursts
|
|
63
|
+
- Faster response times for waiting requests (share result instead of making duplicate calls)
|
|
64
|
+
- Better upstream API utilization with automatic rate smoothing
|
|
65
|
+
- **Deduplicated requests do NOT count against rate limits** - only the first upstream request is rate-limited
|
|
66
|
+
|
|
9
67
|
## [0.4.3] - 2025-09-16
|
|
10
68
|
|
|
11
69
|
### Added
|
{reference_api_buddy-0.4.3/reference_api_buddy.egg-info → reference_api_buddy-0.5.1}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: reference-api-buddy
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.1
|
|
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 ::
|
|
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,22 @@ 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
|
|
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
|
+
## Intstall
|
|
83
|
+
|
|
84
|
+
`pip install reference-api-buddy`
|
|
85
|
+
|
|
86
|
+
[https://pypi.org/project/reference-api-buddy/](https://pypi.org/project/reference-api-buddy/)
|
|
87
|
+
|
|
82
88
|
## Features
|
|
83
89
|
|
|
84
90
|
- **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
|
|
85
|
-
- **
|
|
91
|
+
- **Request Deduplication**: Automatic coalescing of concurrent requests for the same resource to prevent duplicate upstream calls
|
|
92
|
+
- **Fine-Grained Rate Limiting**: Per-second, per-minute, and per-hour rate limits with automatic request throttling (applied only to cache misses)
|
|
93
|
+
- **Progressive Throttling**: Domain-specific rate limiting with exponential backoff
|
|
86
94
|
- **Proxy Security**: Optional secure key authentication to control proxy access
|
|
87
95
|
- **Upstream Pass-through**: Transparent forwarding of API keys and authentication to upstream APIs
|
|
88
96
|
- **Metrics Collection**: Detailed statistics on cache performance, request patterns, and throttling
|
|
@@ -344,11 +352,14 @@ config = {
|
|
|
344
352
|
"domain_mappings": {
|
|
345
353
|
"conceptnet": {
|
|
346
354
|
"upstream": "https://api.conceptnet.io",
|
|
347
|
-
"ttl_seconds": 3600 # 1 hour for frequently changing data
|
|
355
|
+
"ttl_seconds": 3600, # 1 hour for frequently changing data
|
|
356
|
+
"max_requests_per_minute": 60, # Optional: limit to 60 requests per minute
|
|
357
|
+
"max_requests_per_second": 10 # Optional: limit to 10 requests per second
|
|
348
358
|
},
|
|
349
359
|
"wikidata": {
|
|
350
360
|
"upstream": "https://www.wikidata.org",
|
|
351
|
-
"ttl_seconds": 86400 # 1 day for more stable data
|
|
361
|
+
"ttl_seconds": 86400, # 1 day for more stable data
|
|
362
|
+
"max_requests_per_minute": 30 # Optional: limit to 30 requests per minute
|
|
352
363
|
}
|
|
353
364
|
},
|
|
354
365
|
"server": {
|
|
@@ -427,6 +438,142 @@ response4 = requests.get("http://localhost:8080/api/other") # ✗ 429 Throttled
|
|
|
427
438
|
- **Better user experience** - Frequently requested data remains fast
|
|
428
439
|
- **Cost optimization** - Reduces upstream API usage and associated costs
|
|
429
440
|
|
|
441
|
+
### Request Deduplication
|
|
442
|
+
|
|
443
|
+
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.
|
|
444
|
+
|
|
445
|
+
#### How It Works
|
|
446
|
+
|
|
447
|
+
**Automatic Coalescing:**
|
|
448
|
+
- When a cache miss occurs, the proxy checks if another thread is already fetching that resource
|
|
449
|
+
- If yes, subsequent requests **wait** for the first request to complete
|
|
450
|
+
- Once the first request finishes, **all waiting requests** receive the same result
|
|
451
|
+
- The result is then cached for future requests
|
|
452
|
+
|
|
453
|
+
**Example Scenario:**
|
|
454
|
+
|
|
455
|
+
```python
|
|
456
|
+
# Client A, B, and C all request the same resource simultaneously
|
|
457
|
+
# (e.g., from a burst of parallel requests in an LLM pipeline)
|
|
458
|
+
|
|
459
|
+
Client A → Cache miss → Starts fetching from upstream
|
|
460
|
+
Client B → Cache miss → Sees A is fetching, waits for A's result
|
|
461
|
+
Client C → Cache miss → Sees A is fetching, waits for A's result
|
|
462
|
+
|
|
463
|
+
# When A completes:
|
|
464
|
+
A finishes → Returns result to Client A
|
|
465
|
+
→ Returns same result to Client B (deduplicated)
|
|
466
|
+
→ Returns same result to Client C (deduplicated)
|
|
467
|
+
→ Caches result for future requests
|
|
468
|
+
|
|
469
|
+
# Result: Only 1 upstream request instead of 3!
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
#### Benefits
|
|
473
|
+
|
|
474
|
+
- **Reduces upstream load**: Prevents duplicate requests during bursts
|
|
475
|
+
- **Cost savings**: Fewer API calls = lower costs for paid APIs
|
|
476
|
+
- **Faster responses**: Waiting requests get results instantly (no upstream round-trip)
|
|
477
|
+
- **Automatic**: No configuration required, works out of the box
|
|
478
|
+
|
|
479
|
+
#### Error Handling
|
|
480
|
+
|
|
481
|
+
- If the first request fails, the error is propagated to all waiting requests
|
|
482
|
+
- If the first request times out, waiting requests receive a 504 Gateway Timeout
|
|
483
|
+
- Default wait timeout is 60 seconds (configurable per request)
|
|
484
|
+
|
|
485
|
+
**Note**: Deduplication is based on the cache key (URL + method + body), so requests with different parameters are handled independently.
|
|
486
|
+
|
|
487
|
+
---
|
|
488
|
+
|
|
489
|
+
### Fine-Grained Rate Limiting
|
|
490
|
+
|
|
491
|
+
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.
|
|
492
|
+
|
|
493
|
+
#### Configuration
|
|
494
|
+
|
|
495
|
+
Rate limits are configured per-domain in `domain_mappings`:
|
|
496
|
+
|
|
497
|
+
```python
|
|
498
|
+
config = {
|
|
499
|
+
"domain_mappings": {
|
|
500
|
+
"wikidata": {
|
|
501
|
+
"upstream": "https://www.wikidata.org",
|
|
502
|
+
"max_requests_per_minute": 60, # Limit to 60 requests per minute
|
|
503
|
+
"max_requests_per_second": 10 # Limit to 10 requests per second
|
|
504
|
+
},
|
|
505
|
+
"openai": {
|
|
506
|
+
"upstream": "https://api.openai.com",
|
|
507
|
+
"max_requests_per_minute": 500 # Only per-minute limit
|
|
508
|
+
}
|
|
509
|
+
},
|
|
510
|
+
"throttling": {
|
|
511
|
+
"default_requests_per_hour": 1000, # Hour-level limit (all domains)
|
|
512
|
+
"progressive_max_delay": 300, # Max time to wait before returning 429
|
|
513
|
+
"domain_limits": {
|
|
514
|
+
"wikidata": 3000 # Hour-level limit for wikidata specifically
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
#### How It Works
|
|
521
|
+
|
|
522
|
+
**Automatic Request Throttling:**
|
|
523
|
+
- 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)
|
|
524
|
+
- If a delay is needed, the proxy **automatically sleeps** for that duration before making the upstream request
|
|
525
|
+
- The request eventually succeeds (no 429 error returned to client)
|
|
526
|
+
|
|
527
|
+
**Maximum Delay Protection:**
|
|
528
|
+
- If the required delay exceeds `progressive_max_delay` (default 300 seconds), the proxy returns `429 Too Many Requests` instead of waiting
|
|
529
|
+
- This prevents requests from blocking for excessive periods
|
|
530
|
+
|
|
531
|
+
**Multi-Window Priority:**
|
|
532
|
+
- The system checks all configured time windows and uses the **maximum delay** required across all windows
|
|
533
|
+
- Example: If per-second limit needs 0.5s delay and per-minute limit needs 5s delay, the proxy waits 5 seconds
|
|
534
|
+
|
|
535
|
+
**Example Flow:**
|
|
536
|
+
|
|
537
|
+
```python
|
|
538
|
+
# With max_requests_per_second: 2 configured
|
|
539
|
+
proxy.start(blocking=False)
|
|
540
|
+
|
|
541
|
+
# Request 1 - No delay, immediate
|
|
542
|
+
response1 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
|
|
543
|
+
|
|
544
|
+
# Request 2 - No delay, immediate
|
|
545
|
+
response2 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
|
|
546
|
+
|
|
547
|
+
# Request 3 - Automatic delay before upstream request
|
|
548
|
+
response3 = requests.get("http://localhost:8080/wikidata/query?...") # Waits ~1 second, then completes
|
|
549
|
+
|
|
550
|
+
# Cache hits are NEVER delayed
|
|
551
|
+
cached = requests.get("http://localhost:8080/wikidata/query?...") # Instant (cache hit)
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
#### Use Cases
|
|
555
|
+
|
|
556
|
+
**Per-Second Limits:**
|
|
557
|
+
- Prevent request bursts
|
|
558
|
+
- Smooth out traffic to upstream APIs
|
|
559
|
+
- Comply with strict burst rate limits
|
|
560
|
+
|
|
561
|
+
**Per-Minute Limits:**
|
|
562
|
+
- Control sustained request rates
|
|
563
|
+
- Stay within API tier limits (e.g., "60 requests per minute")
|
|
564
|
+
- Avoid triggering upstream rate limiters
|
|
565
|
+
|
|
566
|
+
**Combined Limits:**
|
|
567
|
+
- Enforce both burst protection (per-second) and sustained rate control (per-minute/hour)
|
|
568
|
+
- Example: "Max 10 req/sec, 300 req/min, 5000 req/hour"
|
|
569
|
+
|
|
570
|
+
#### Configuration Notes
|
|
571
|
+
|
|
572
|
+
- All rate limit parameters are **optional**
|
|
573
|
+
- Rate limits apply **only to cache misses** (cache hits bypass all throttling)
|
|
574
|
+
- Parameters only need to be specified for domains that require rate limiting
|
|
575
|
+
- If not specified, only the hour-level throttling applies (via `throttling.domain_limits`)
|
|
576
|
+
|
|
430
577
|
### TTL (Time To Live) Configuration
|
|
431
578
|
|
|
432
579
|
The proxy supports flexible TTL configuration at both system-wide and per-domain levels:
|
|
@@ -1,13 +1,21 @@
|
|
|
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
|
|
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
|
+
## Intstall
|
|
8
|
+
|
|
9
|
+
`pip install reference-api-buddy`
|
|
10
|
+
|
|
11
|
+
[https://pypi.org/project/reference-api-buddy/](https://pypi.org/project/reference-api-buddy/)
|
|
12
|
+
|
|
7
13
|
## Features
|
|
8
14
|
|
|
9
15
|
- **Persistent Caching**: Persistent SQLite-based cache (in-memory or on-disk) with configurable TTL and compression
|
|
10
|
-
- **
|
|
16
|
+
- **Request Deduplication**: Automatic coalescing of concurrent requests for the same resource to prevent duplicate upstream calls
|
|
17
|
+
- **Fine-Grained Rate Limiting**: Per-second, per-minute, and per-hour rate limits with automatic request throttling (applied only to cache misses)
|
|
18
|
+
- **Progressive Throttling**: Domain-specific rate limiting with exponential backoff
|
|
11
19
|
- **Proxy Security**: Optional secure key authentication to control proxy access
|
|
12
20
|
- **Upstream Pass-through**: Transparent forwarding of API keys and authentication to upstream APIs
|
|
13
21
|
- **Metrics Collection**: Detailed statistics on cache performance, request patterns, and throttling
|
|
@@ -269,11 +277,14 @@ config = {
|
|
|
269
277
|
"domain_mappings": {
|
|
270
278
|
"conceptnet": {
|
|
271
279
|
"upstream": "https://api.conceptnet.io",
|
|
272
|
-
"ttl_seconds": 3600 # 1 hour for frequently changing data
|
|
280
|
+
"ttl_seconds": 3600, # 1 hour for frequently changing data
|
|
281
|
+
"max_requests_per_minute": 60, # Optional: limit to 60 requests per minute
|
|
282
|
+
"max_requests_per_second": 10 # Optional: limit to 10 requests per second
|
|
273
283
|
},
|
|
274
284
|
"wikidata": {
|
|
275
285
|
"upstream": "https://www.wikidata.org",
|
|
276
|
-
"ttl_seconds": 86400 # 1 day for more stable data
|
|
286
|
+
"ttl_seconds": 86400, # 1 day for more stable data
|
|
287
|
+
"max_requests_per_minute": 30 # Optional: limit to 30 requests per minute
|
|
277
288
|
}
|
|
278
289
|
},
|
|
279
290
|
"server": {
|
|
@@ -352,6 +363,142 @@ response4 = requests.get("http://localhost:8080/api/other") # ✗ 429 Throttled
|
|
|
352
363
|
- **Better user experience** - Frequently requested data remains fast
|
|
353
364
|
- **Cost optimization** - Reduces upstream API usage and associated costs
|
|
354
365
|
|
|
366
|
+
### Request Deduplication
|
|
367
|
+
|
|
368
|
+
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.
|
|
369
|
+
|
|
370
|
+
#### How It Works
|
|
371
|
+
|
|
372
|
+
**Automatic Coalescing:**
|
|
373
|
+
- When a cache miss occurs, the proxy checks if another thread is already fetching that resource
|
|
374
|
+
- If yes, subsequent requests **wait** for the first request to complete
|
|
375
|
+
- Once the first request finishes, **all waiting requests** receive the same result
|
|
376
|
+
- The result is then cached for future requests
|
|
377
|
+
|
|
378
|
+
**Example Scenario:**
|
|
379
|
+
|
|
380
|
+
```python
|
|
381
|
+
# Client A, B, and C all request the same resource simultaneously
|
|
382
|
+
# (e.g., from a burst of parallel requests in an LLM pipeline)
|
|
383
|
+
|
|
384
|
+
Client A → Cache miss → Starts fetching from upstream
|
|
385
|
+
Client B → Cache miss → Sees A is fetching, waits for A's result
|
|
386
|
+
Client C → Cache miss → Sees A is fetching, waits for A's result
|
|
387
|
+
|
|
388
|
+
# When A completes:
|
|
389
|
+
A finishes → Returns result to Client A
|
|
390
|
+
→ Returns same result to Client B (deduplicated)
|
|
391
|
+
→ Returns same result to Client C (deduplicated)
|
|
392
|
+
→ Caches result for future requests
|
|
393
|
+
|
|
394
|
+
# Result: Only 1 upstream request instead of 3!
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
#### Benefits
|
|
398
|
+
|
|
399
|
+
- **Reduces upstream load**: Prevents duplicate requests during bursts
|
|
400
|
+
- **Cost savings**: Fewer API calls = lower costs for paid APIs
|
|
401
|
+
- **Faster responses**: Waiting requests get results instantly (no upstream round-trip)
|
|
402
|
+
- **Automatic**: No configuration required, works out of the box
|
|
403
|
+
|
|
404
|
+
#### Error Handling
|
|
405
|
+
|
|
406
|
+
- If the first request fails, the error is propagated to all waiting requests
|
|
407
|
+
- If the first request times out, waiting requests receive a 504 Gateway Timeout
|
|
408
|
+
- Default wait timeout is 60 seconds (configurable per request)
|
|
409
|
+
|
|
410
|
+
**Note**: Deduplication is based on the cache key (URL + method + body), so requests with different parameters are handled independently.
|
|
411
|
+
|
|
412
|
+
---
|
|
413
|
+
|
|
414
|
+
### Fine-Grained Rate Limiting
|
|
415
|
+
|
|
416
|
+
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.
|
|
417
|
+
|
|
418
|
+
#### Configuration
|
|
419
|
+
|
|
420
|
+
Rate limits are configured per-domain in `domain_mappings`:
|
|
421
|
+
|
|
422
|
+
```python
|
|
423
|
+
config = {
|
|
424
|
+
"domain_mappings": {
|
|
425
|
+
"wikidata": {
|
|
426
|
+
"upstream": "https://www.wikidata.org",
|
|
427
|
+
"max_requests_per_minute": 60, # Limit to 60 requests per minute
|
|
428
|
+
"max_requests_per_second": 10 # Limit to 10 requests per second
|
|
429
|
+
},
|
|
430
|
+
"openai": {
|
|
431
|
+
"upstream": "https://api.openai.com",
|
|
432
|
+
"max_requests_per_minute": 500 # Only per-minute limit
|
|
433
|
+
}
|
|
434
|
+
},
|
|
435
|
+
"throttling": {
|
|
436
|
+
"default_requests_per_hour": 1000, # Hour-level limit (all domains)
|
|
437
|
+
"progressive_max_delay": 300, # Max time to wait before returning 429
|
|
438
|
+
"domain_limits": {
|
|
439
|
+
"wikidata": 3000 # Hour-level limit for wikidata specifically
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
#### How It Works
|
|
446
|
+
|
|
447
|
+
**Automatic Request Throttling:**
|
|
448
|
+
- 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)
|
|
449
|
+
- If a delay is needed, the proxy **automatically sleeps** for that duration before making the upstream request
|
|
450
|
+
- The request eventually succeeds (no 429 error returned to client)
|
|
451
|
+
|
|
452
|
+
**Maximum Delay Protection:**
|
|
453
|
+
- If the required delay exceeds `progressive_max_delay` (default 300 seconds), the proxy returns `429 Too Many Requests` instead of waiting
|
|
454
|
+
- This prevents requests from blocking for excessive periods
|
|
455
|
+
|
|
456
|
+
**Multi-Window Priority:**
|
|
457
|
+
- The system checks all configured time windows and uses the **maximum delay** required across all windows
|
|
458
|
+
- Example: If per-second limit needs 0.5s delay and per-minute limit needs 5s delay, the proxy waits 5 seconds
|
|
459
|
+
|
|
460
|
+
**Example Flow:**
|
|
461
|
+
|
|
462
|
+
```python
|
|
463
|
+
# With max_requests_per_second: 2 configured
|
|
464
|
+
proxy.start(blocking=False)
|
|
465
|
+
|
|
466
|
+
# Request 1 - No delay, immediate
|
|
467
|
+
response1 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
|
|
468
|
+
|
|
469
|
+
# Request 2 - No delay, immediate
|
|
470
|
+
response2 = requests.get("http://localhost:8080/wikidata/query?...") # Instant
|
|
471
|
+
|
|
472
|
+
# Request 3 - Automatic delay before upstream request
|
|
473
|
+
response3 = requests.get("http://localhost:8080/wikidata/query?...") # Waits ~1 second, then completes
|
|
474
|
+
|
|
475
|
+
# Cache hits are NEVER delayed
|
|
476
|
+
cached = requests.get("http://localhost:8080/wikidata/query?...") # Instant (cache hit)
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
#### Use Cases
|
|
480
|
+
|
|
481
|
+
**Per-Second Limits:**
|
|
482
|
+
- Prevent request bursts
|
|
483
|
+
- Smooth out traffic to upstream APIs
|
|
484
|
+
- Comply with strict burst rate limits
|
|
485
|
+
|
|
486
|
+
**Per-Minute Limits:**
|
|
487
|
+
- Control sustained request rates
|
|
488
|
+
- Stay within API tier limits (e.g., "60 requests per minute")
|
|
489
|
+
- Avoid triggering upstream rate limiters
|
|
490
|
+
|
|
491
|
+
**Combined Limits:**
|
|
492
|
+
- Enforce both burst protection (per-second) and sustained rate control (per-minute/hour)
|
|
493
|
+
- Example: "Max 10 req/sec, 300 req/min, 5000 req/hour"
|
|
494
|
+
|
|
495
|
+
#### Configuration Notes
|
|
496
|
+
|
|
497
|
+
- All rate limit parameters are **optional**
|
|
498
|
+
- Rate limits apply **only to cache misses** (cache hits bypass all throttling)
|
|
499
|
+
- Parameters only need to be specified for domains that require rate limiting
|
|
500
|
+
- If not specified, only the hour-level throttling applies (via `throttling.domain_limits`)
|
|
501
|
+
|
|
355
502
|
### TTL (Time To Live) Configuration
|
|
356
503
|
|
|
357
504
|
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.
|
|
7
|
+
version = "0.5.1"
|
|
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 ::
|
|
18
|
+
"Development Status :: 4 - Beta",
|
|
19
19
|
"Intended Audience :: Developers",
|
|
20
20
|
"License :: OSI Approved :: MIT License",
|
|
21
21
|
"Programming Language :: Python :: 3",
|
|
@@ -9,7 +9,7 @@ from reference_api_buddy.core.proxy import CachingProxy, SecurityError
|
|
|
9
9
|
from reference_api_buddy.security.manager import SecurityManager
|
|
10
10
|
from reference_api_buddy.throttling.manager import ThrottleManager
|
|
11
11
|
|
|
12
|
-
__version__ = "0.
|
|
12
|
+
__version__ = "0.5.1"
|
|
13
13
|
__author__ = "Reference API Buddy Team"
|
|
14
14
|
__email__ = "contact@example.com"
|
|
15
15
|
|
|
@@ -10,6 +10,7 @@ DEFAULT_CONFIG = {
|
|
|
10
10
|
"cache": {
|
|
11
11
|
"database_path": ":memory:",
|
|
12
12
|
"max_cache_response_size": 10485760, # 10MB
|
|
13
|
+
"max_cache_entries": 1000, # LRU eviction beyond this many entries
|
|
13
14
|
"default_ttl_seconds": 86400, # 1 day = 24 * 3600 seconds
|
|
14
15
|
},
|
|
15
16
|
"throttling": {"default_requests_per_hour": 1000, "progressive_max_delay": 300},
|
|
@@ -74,6 +75,11 @@ class ConfigurationValidator:
|
|
|
74
75
|
errors.append("cache.database_path must be a string.")
|
|
75
76
|
if not isinstance(cache.get("max_cache_response_size", None), int):
|
|
76
77
|
errors.append("cache.max_cache_response_size must be an integer.")
|
|
78
|
+
max_entries = cache.get("max_cache_entries")
|
|
79
|
+
if max_entries is not None and (
|
|
80
|
+
isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries <= 0
|
|
81
|
+
):
|
|
82
|
+
errors.append("cache.max_cache_entries must be a positive integer.")
|
|
77
83
|
|
|
78
84
|
# Validate cache TTL
|
|
79
85
|
default_ttl = cache.get("default_ttl_seconds")
|
|
@@ -107,7 +113,7 @@ class ConfigurationValidator:
|
|
|
107
113
|
if not isinstance(logging_cfg.get("backup_count", None), int):
|
|
108
114
|
errors.append("logging.backup_count must be an integer.")
|
|
109
115
|
|
|
110
|
-
# Validate domain-specific TTL
|
|
116
|
+
# Validate domain-specific TTL and rate limits
|
|
111
117
|
domain_mappings = config.get("domain_mappings", {})
|
|
112
118
|
for domain_key, mapping in domain_mappings.items():
|
|
113
119
|
if isinstance(mapping, dict):
|
|
@@ -115,6 +121,16 @@ class ConfigurationValidator:
|
|
|
115
121
|
if ttl is not None and (not isinstance(ttl, int) or ttl <= 0):
|
|
116
122
|
errors.append(f"domain_mappings.{domain_key}.ttl_seconds must be a positive integer.")
|
|
117
123
|
|
|
124
|
+
# Validate max_requests_per_minute
|
|
125
|
+
rpm = mapping.get("max_requests_per_minute")
|
|
126
|
+
if rpm is not None and (not isinstance(rpm, int) or rpm <= 0):
|
|
127
|
+
errors.append(f"domain_mappings.{domain_key}.max_requests_per_minute must be a positive integer.")
|
|
128
|
+
|
|
129
|
+
# Validate max_requests_per_second
|
|
130
|
+
rps = mapping.get("max_requests_per_second")
|
|
131
|
+
if rps is not None and (not isinstance(rps, int) or rps <= 0):
|
|
132
|
+
errors.append(f"domain_mappings.{domain_key}.max_requests_per_second must be a positive integer.")
|
|
133
|
+
|
|
118
134
|
# Validate admin configuration
|
|
119
135
|
admin = config.get("admin", {})
|
|
120
136
|
if not isinstance(admin.get("enabled", None), bool):
|