At 09:00:03, a monitoring script receives its first successful response. Eighteen seconds later, the same script starts receiving HTTP 429 responses with code: 3001. The API key is valid, the symbol is valid, and the code has not changed. The only meaningful variable is request frequency.
Free API tiers are often evaluated with a single question: “How much data can I get?” That question is incomplete for real-time systems. The practical questions are how many requests remain within a rolling window, what happens when the limit is reached, whether the WebSocket connection receives a graceful close, and how a client should recover without creating a retry storm.
This review examines the free tier as an engineering boundary rather than a headline quota. It covers daily request consumption, endpoint-specific allowances, WebSocket connection behavior, rate-limit responses, Retry-After, and the recovery logic required for a reliable client. The conclusions distinguish documented TickDB behavior from measurements that must be performed against the current account configuration.
1. The Free Tier Is a Traffic-Shaping System
The free tier is not simply a smaller version of a production data plan. It is a shared environment with finite capacity, request accounting, and protection mechanisms designed to keep one client from degrading the experience for others.
That distinction determines how you should test the service. A successful request proves that authentication and the endpoint work. It does not reveal the number of calls included in the daily allowance, whether the allowance resets on a fixed calendar boundary or a rolling window, or whether the same limit applies to REST and WebSocket traffic.
The distinction also determines how you should design production-like code. A client that retries immediately after a rate-limit response can turn a controlled throttle into an overloaded account. A client that assumes every WebSocket connection has the same allowance can mistake a server-side close for a network failure and reconnect too aggressively.
The correct evaluation framework is therefore:
| Dimension | What to measure | Why it matters |
|---|---|---|
| Daily request allowance | Successful and rejected requests over a controlled window | Establishes capacity for dashboards, alerts, and scheduled jobs |
| Window behavior | Remaining quota before and after the reset | Prevents bursty workloads from exceeding an undocumented boundary |
| Endpoint sensitivity | Behavior across REST and WebSocket | Some operations consume different server resources |
| Rate-limit response | Status code, body fields, and headers | Determines whether the client can recover automatically |
| Recovery behavior | Delay before retry and subsequent request outcome | Separates graceful throttling from retry amplification |
| WebSocket lifecycle | Session duration, close code, and reconnect behavior | Determines whether streaming code can run unattended |
The table separates measurable behavior from assumptions. TickDB’s documented interface rules provide the foundation, but the exact free-tier allowance and enforcement thresholds must be verified against the current account configuration. Treating an undocumented number as a permanent product fact would make a test report misleading.
2. REST Limits, WebSocket Limits, and the Retry-After Contract
TickDB exposes two authentication models, and confusing them is one of the most common sources of apparently broken integrations:
- REST requests use the
X-API-Keyrequest header. - WebSocket connections authenticate through the
?api_key=query parameter.
The REST error model identifies rate-limit events with code: 3001. A client should read the Retry-After response header and wait before issuing another request. The retry delay must come from the server response when available; a fixed one-second retry is not a substitute for the advertised delay.
A typical REST response should be handled in the following order:
def parse_response(response, symbol=None):
payload = response.json()
if response.status_code == 429 or payload.get("code") == 3001:
retry_after = response.headers.get("Retry-After", "5")
return {
"state": "rate_limited",
"retry_after": retry_after,
"payload": payload,
}
if response.status_code >= 400:
raise RuntimeError(
f"TickDB request failed: HTTP {response.status_code}, "
f"payload={payload}"
)
if payload.get("code", 0) != 0:
raise RuntimeError(f"TickDB API error: {payload}")
return payload.get("data")
The code: 3001 check matters because some gateways preserve the API error body while using a conventional HTTP status code. A client that checks only response.status_code can therefore miss a rate-limit event in some implementations.
2.1 Daily Quota and Remaining Calls
The daily allowance is an account entitlement, not a property of the endpoint implementation. The authoritative value for a particular account may be exposed in the dashboard, in an entitlement endpoint, or in response headers. If the dashboard does not display it, the only reliable approach is to measure consumption using a controlled test rather than guess from documentation written for another tier or another period.
The following small test estimates the visible quota state without deliberately exhausting the allowance:
import os
import time
from datetime import datetime, timezone
import requests
BASE_URL = "https://api.tickdb.ai"
API_KEY = os.environ.get("TICKDB_API_KEY")
if not API_KEY:
raise RuntimeError(
"TICKDB_API_KEY is required. "
"Set it before running this quota probe."
)
session = requests.Session()
session.headers.update({"X-API-Key": API_KEY})
headers_to_watch = (
"Retry-After",
"X-RateLimit-Limit",
"X-RateLimit-Remaining",
"X-RateLimit-Reset",
"RateLimit-Limit",
"RateLimit-Remaining",
"RateLimit-Reset",
)
def read_rate_headers(response):
return {
name: response.headers[name]
for name in headers_to_watch
if name in response.headers
}
def probe(symbol="AAPL.US", interval="1h", limit=10):
response = session.get(
f"{BASE_URL}/v1/market/kline",
params={
"symbol": symbol,
"interval": interval,
"limit": limit,
},
timeout=(3.05, 10),
)
print({
"timestamp": datetime.now(timezone.utc).isoformat(),
"http_status": response.status_code,
"rate_headers": read_rate_headers(response),
})
if response.status_code == 429:
body = response.json()
print({
"state": "rate_limited",
"code": body.get("code"),
"retry_after": response.headers.get("Retry-After"),
"message": body.get("message"),
})
return
response.raise_for_status()
print(response.json())
if __name__ == "__main__":
probe()
This probe is intentionally conservative. It performs one request and displays quota headers if the service exposes them. Repeated calls consume the same daily allowance as any other client, so testing should stop once the account reaches a rate-limit response.
2.2 A Practical Measurement Protocol
Use the following procedure when documenting the current behavior of a free-tier account:
| Step | Action | Measurement |
|---|---|---|
| 1 | Record the account’s visible quota before testing | Remaining calls and reset time |
| 2 | Send one authenticated REST request | Status, response shape, and rate headers |
| 3 | Send a small controlled burst | First request index that returns 3001 |
| 4 | Record Retry-After |
Minimum server-requested delay |
| 5 | Wait exactly the requested delay | Whether the next request succeeds |
| 6 | Repeat during a later window | Whether the allowance resets and how |
| 7 | Run a separate WebSocket session | Connection duration, close code, and error payload |
The first rejected request establishes only an observed boundary. It does not prove that every free account receives the same boundary, and it does not distinguish a daily quota from a short-window burst limit. To identify both controls, record timestamps and compare behavior across a window long enough to cover the suspected reset interval.
A useful report includes the following fields:
account_tier: free
tested_at_utc: 2026-04-15T09:00:03Z
rest_endpoint: /v1/market/kline
requests_before_first_3001: [observed value]
first_rate_limit_at: [timestamp]
retry_after_seconds: [observed value]
success_after_retry_after: true/false
websocket_close_code: [observed value]
websocket_reconnect_succeeded: true/false
The important operational conclusion is not the value printed in the report. It is that the client must treat the quota as discoverable account state and handle a refusal without assuming that every refusal has the same cause.
3. What Happens When the Limit Is Triggered?
A rate-limit response has three parts: the transport signal, the TickDB error body, and the recovery instruction.
The transport signal is normally an HTTP 429 response for REST requests. The TickDB body identifies the condition with code: 3001. The recovery instruction normally appears in the Retry-After header. The client should treat these signals as related and should not discard the body merely because the HTTP status is available.
3.1 REST Recovery Logic
A resilient REST client should:
- Send the API key through
X-API-Key. - Apply a timeout to every request.
- Detect both HTTP 429 and TickDB
code: 3001. - Read
Retry-After. - Stop sending requests until the delay expires.
- Retry at most once per request unless the service provides a new instruction.
- Preserve the original error for observability.
The following implementation demonstrates that sequence:
import os
import time
from datetime import datetime, timezone
import requests
BASE_URL = "https://api.tickdb.ai"
API_KEY = os.environ.get("TICKDB_API_KEY")
if not API_KEY:
raise RuntimeError("TICKDB_API_KEY is not configured")
session = requests.Session()
session.headers.update({"X-API-Key": API_KEY})
def get_kline(symbol, interval="1h", limit=100):
url = f"{BASE_URL}/v1/market/kline"
params = {
"symbol": symbol,
"interval": interval,
"limit": limit,
}
for attempt in range(2):
response = session.get(
url,
params=params,
timeout=(3.05, 10),
)
if response.status_code == 429:
retry_after = response.headers.get("Retry-After", "5")
delay = max(0, int(retry_after))
print(
f"Rate limited at {datetime.now(timezone.utc).isoformat()}; "
f"waiting {delay}s"
)
time.sleep(delay)
continue
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError("TickDB returned a non-JSON error") from exc
if response.status_code >= 400:
raise RuntimeError(
f"HTTP {response.status_code}: {payload.get('message', payload)}"
)
if payload.get("code") == 3001:
retry_after = payload.get("retry_after", 5)
time.sleep(max(0, int(retry_after)))
continue
if payload.get("code", 0) != 0:
raise RuntimeError(f"TickDB error: {payload}")
return payload.get("data")
raise RuntimeError("TickDB rate limit persisted after the permitted retry")
The one-retry limit is deliberate. A client that repeats the request indefinitely after a rate-limit response can create a hot loop, especially when several workers share the same API key. The server’s Retry-After value is the instruction to pause; it is not an invitation to send a parallel burst.
3.2 Error Classification
The application should distinguish four failure classes:
| Classification | Signal | Recovery |
|---|---|---|
| Authentication failure | 1001 or 1002 |
Stop. Check TICKDB_API_KEY; do not retry automatically. |
| Symbol failure | 2002 |
Verify the symbol through /v1/symbols/available; do not retry unchanged. |
| Rate limit | 3001 or HTTP 429 |
Read Retry-After, pause, then retry within policy. |
| Transport failure | Timeout, DNS, reset connection | Retry with bounded exponential backoff and jitter. |
This distinction prevents a malformed request from consuming the same retry budget as a temporary server-side throttle.
4. WebSocket Duration: Connection Lifetime Is Not Quota Lifetime
A WebSocket connection should not be modeled as a request counter. Opening a stream establishes a session that may remain active while the server sends updates. The relevant questions are different:
- Does the free tier impose a maximum connection duration?
- Does the server close idle sessions?
- Are subscription messages counted against the same request allowance as REST calls?
- Does a rate-limit condition close the socket, emit a message, or pause delivery?
- What close code does the server send?
The connection lifetime must therefore be observed under a declared test condition. A useful test records heartbeat cadence, the number of messages received, the duration of the session, and the exact close reason.
The following client is designed for a TickDB WebSocket endpoint whose URL is supplied through the environment. This avoids hardcoding an endpoint that may vary by deployment or account configuration.
import asyncio
import json
import os
import random
import time
from datetime import datetime, timezone
from urllib.parse import urlencode
import websockets
WS_URL = os.environ.get("TICKDB_WS_URL")
API_KEY = os.environ.get("TICKDB_API_KEY")
SUBSCRIBE_PAYLOAD = os.environ.get("TICKDB_SUBSCRIBE_PAYLOAD")
if not WS_URL:
raise RuntimeError("TICKDB_WS_URL is required")
if not API_KEY:
raise RuntimeError("TICKDB_API_KEY is required")
if not SUBSCRIBE_PAYLOAD:
raise RuntimeError("TICKDB_SUBSCRIBE_PAYLOAD is required")
def authenticated_url(url):
separator = "&" if "?" in url else "?"
return f"{url}{separator}{urlencode({'api_key': API_KEY})}"
async def send_json(websocket, payload):
await asyncio.wait_for(
websocket.send(json.dumps(payload)),
timeout=10,
)
async def consume_stream():
retry = 0
base_delay = 1
max_delay = 60
while True:
url = authenticated_url(WS_URL)
try:
async with websockets.connect(
url,
open_timeout=10,
close_timeout=5,
ping_interval=20,
ping_timeout=10,
) as websocket:
retry = 0
connected_at = time.monotonic()
print(
f"WebSocket connected at "
f"{datetime.now(timezone.utc).isoformat()}"
)
await send_json(websocket, json.loads(SUBSCRIBE_PAYLOAD))
heartbeat_task = asyncio.create_task(
heartbeat(websocket)
)
try:
async for raw_message in websocket:
message = parse_message(raw_message)
if message.get("code") == 3001:
retry_after = extract_retry_after(message)
print(
f"WebSocket rate limit signal; "
f"waiting {retry_after}s"
)
await asyncio.sleep(retry_after)
continue
if message.get("code", 0) not in (0, None):
raise RuntimeError(
f"WebSocket API error: {message}"
)
print(message)
finally:
heartbeat_task.cancel()
await asyncio.gather(
heartbeat_task,
return_exceptions=True,
)
print(
f"WebSocket closed after "
f"{time.monotonic() - connected_at:.1f}s"
)
except (OSError, asyncio.TimeoutError, websockets.WebSocketException) as exc:
delay = min(base_delay * (2 ** retry), max_delay)
jitter = random.uniform(0, delay * 0.1)
retry += 1
print(
f"WebSocket failure: {exc}; "
f"reconnecting in {delay + jitter:.2f}s"
)
await asyncio.sleep(delay + jitter)
async def heartbeat(websocket):
while True:
await asyncio.sleep(15)
await send_json(websocket, {"cmd": "ping"})
def parse_message(raw_message):
if isinstance(raw_message, bytes):
raw_message = raw_message.decode("utf-8")
try:
return json.loads(raw_message)
except json.JSONDecodeError:
return {"raw": raw_message}
def extract_retry_after(message):
value = message.get("retry_after", 5)
try:
return max(0, int(value))
except (TypeError, ValueError):
return 5
if __name__ == "__main__":
try:
asyncio.run(consume_stream())
except KeyboardInterrupt:
print("WebSocket client stopped")
The client includes five production requirements:
- It authenticates through the WebSocket query parameter.
- It sends an application-level
{"cmd": "ping"}heartbeat. - It reconnects with exponential backoff and jitter.
- It handles a
3001message with a server-provided or conservativeretry_afterdelay. - It never prints the authenticated URL, preventing the API key from appearing in ordinary logs.
The code also acknowledges an important protocol detail: WebSocket servers do not expose HTTP response headers in the same way as REST responses. If the service communicates the delay inside the WebSocket message, the client reads retry_after; if it closes the connection instead, the reconnect path must use a conservative delay rather than assuming that the header survived the protocol transition.
4.1 WebSocket Test Matrix
Run the stream client under controlled conditions and record the results:
| Test | Variable | Expected observation |
|---|---|---|
| W1 | Active subscription | Messages arrive and heartbeat responses remain healthy |
| W2 | No data for 30 minutes | Connection stays alive or closes with a documented idle policy |
| W3 | Sustained session duration | Record exact uptime and close code |
| W4 | Multiple concurrent sessions | Record whether concurrency is accepted or rejected |
| W5 | Session opened near the daily boundary | Determine whether quota state affects admission |
| W6 | Simulated client failure | Reconnect delay increases and remains jittered |
A single successful WebSocket session does not establish a maximum duration. If the free tier uses a session timeout, the test should continue until the server closes the connection and capture the close code and reason. If the service does not impose a fixed duration, record that as an observation for the tested account and date rather than a permanent guarantee.
5. Order Book and Market-Data Boundaries
TickDB’s data capabilities affect which free-tier workloads are technically meaningful. The depth channel is supported for US equities at L1, for Hong Kong equities at L1–L10, and for crypto at L1–L10. It is not supported for forex, precious metals, or indices.
That boundary is more important than a raw request count. A plan can have ample calls and still be unsuitable for a strategy if the required data is not available.
| Data requirement | TickDB boundary | Free-tier implication |
|---|---|---|
| US equity historical OHLCV | Supported through /v1/market/kline |
Suitable for lightweight historical studies within quota |
| US equity tick-level trades | Not supported through the trades endpoint |
A trade-tick strategy cannot be migrated directly |
| Hong Kong equity depth | L1–L10 supported | Multi-level snapshots can be tested where appropriate |
| Crypto depth | L1–L10 supported | Order-flow experiments are technically possible |
| US equity depth | L1 supported | Use for top-of-book monitoring, not multi-level US analysis |
| Forex, precious metals, and indices depth | Not supported | Do not design a depth strategy around these symbols |
The WebSocket stream should also be scoped to actual analytical needs. A client that subscribes to multiple symbols and depth levels may consume more bandwidth and server resources than a single-symbol monitor. A free-tier evaluation should compare the alert latency you need with the number of messages you actually consume.
For a simple L1 monitor, calculate a pressure ratio from the best bid and ask:
def pressure_ratio(bid_size, ask_size):
if ask_size <= 0:
raise ValueError("ask_size must be positive")
return bid_size / ask_size
For a multi-level feed, use a depth window appropriate to the supported market:
def aggregate_pressure(bids, asks, levels=5):
bid_volume = sum(level["size"] for level in bids[:levels])
ask_volume = sum(level["size"] for level in asks[:levels])
if ask_volume <= 0:
return float("inf")
return bid_volume / ask_volume
These calculations are useful only if the data feed is delivering the levels you believe it is delivering. Log the symbol, subscribed channel, message count, and timestamp source during validation. A rate-limit test should not double as a data-quality test.
6. Free Tier Compared with Production Expectations
The relevant comparison is not “free versus expensive.” It is between workload shape and service boundary.
| Workload | Free-tier fit | Main limitation | Recommended design |
|---|---|---|---|
| Personal OHLCV dashboard | Good for intermittent requests | Daily call budget | Cache responses and poll only when needed |
| Single-symbol L1 alert | Suitable for lightweight monitoring | Session duration and message rate | Use heartbeat, bounded reconnects, and alert deduplication |
| Multi-symbol crypto monitor | Possible, but resource-heavy | Concurrent subscriptions and quota | Limit subscriptions and batch downstream work |
| Multi-level Hong Kong depth study | Technically supported | Depth data volume and quota | Record the exact level requirement before subscribing |
| US equity tick-trades strategy | Not supported by the trades endpoint |
Data capability mismatch | Use supported historical or depth data instead |
| Institutional multi-tenant service | Poor fit for the free tier | Quota, concurrency, and operational isolation | Use a dedicated plan and separate service accounts |
A free-tier client should also cache successful historical responses when the strategy permits it. Caching reduces unnecessary calls, improves latency, and prevents a dashboard refresh from competing with a real-time alert process.
The most important engineering distinction is between a rate limit and a data limitation. A rate limit is recoverable through pacing and Retry-After. A data limitation requires a different endpoint, symbol universe, or strategy design.
7. Deployment Guide for the Free Tier
A minimal free-tier deployment should separate data acquisition, analysis, and delivery into distinct components:
┌──────────────────────┐
│ Scheduler / Caller │
│ - deduplicate calls │
│ - cache responses │
└──────────┬───────────┘
│ authenticated REST
▼
┌──────────────────────┐
│ TickDB Client │
│ - X-API-Key │
│ - request timeout │
│ - 3001 handling │
│ - Retry-After │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Data Processing │
│ - OHLCV / depth │
│ - pressure metrics │
│ - timestamp checks │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Delivery Layer │
│ - alerts │
│ - dashboards │
│ - local cache │
└──────────────────────┘
Use the following configuration pattern:
| Component | Individual developer | Small team | Production service |
|---|---|---|---|
| API key | One key per environment | Separate development and production keys | Dedicated service identity |
| Request scheduling | Manual or cached polling | Centralized scheduler | Rate-aware job queue |
| WebSocket sessions | One symbol or a small set | One client per strategy family | Horizontally scalable consumer with shared offsets |
| Alerting | Local logs and webhooks | Central alert service | Deduplicated incident pipeline |
| Quota monitoring | Manual dashboard check | Scheduled quota probe | Header and error-event telemetry |
| Failure policy | Stop after one retry | Exponential backoff | Bounded backoff, circuit breaker, and operator visibility |
Environment variables should keep credentials out of source control:
export TICKDB_API_KEY="your_api_key"
export TICKDB_WS_URL="your_configured_websocket_endpoint"
export TICKDB_SUBSCRIBE_PAYLOAD='{"cmd":"subscribe","channel":"depth","symbol":"AAPL.US"}'
The subscription payload above is an example configuration shape. The exact channel and symbol fields must match the WebSocket command schema supported by the current account and market. Do not copy it blindly into production.
A small operational checklist should answer these questions every day:
- How many REST calls did the client make?
- How many WebSocket messages were consumed?
- How many
3001responses occurred? - What was the maximum observed
Retry-Aftervalue? - Did the client reconnect successfully after each disconnect?
- Are quota headers or dashboard counters changing as expected?
- Did any process exceed its retry budget?
- Is the account using a symbol or data type that TickDB does not support?
8. Final Assessment
A free API is useful when its boundaries are visible. The first successful response tells you that the endpoint works; it does not tell you how far a burst can travel or whether a WebSocket session remains available indefinitely.
The operational rules are straightforward. Read the Retry-After header when REST returns 3001. Pause the exact amount of time the server requests. Keep reconnect delays exponential and jittered. Treat WebSocket session duration as a measured account behavior, not a permanent constant. Respect the documented data boundaries before optimizing request efficiency.
The practical free-tier decision should therefore use four numbers from your own account: observed requests before the first 3001, the observed Retry-After, the measured WebSocket uptime, and the number of messages consumed per hour. Those values reveal whether the account fits a personal dashboard, a research notebook, or a continuously running monitoring process.
Next Steps
If you are evaluating a personal data workflow, start with the REST quota probe, cache historical responses, and keep the first WebSocket subscription limited to one symbol or one required depth channel.
If you want to run the examples, sign up at tickdb.ai, create an API key, set TICKDB_API_KEY, and copy the production-grade code from this article.
If you need a reliable multi-tenant or high-concurrency service, contact [email protected] for an institutional data plan and a deployment review.
If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your AI tool’s marketplace.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.