Create a secure partner data exchange: quotas, cost limits, auditing, and revocation.
- User
Create a secure partner data exchange: quotas, cost limits, auditing, and revocation.
- Assistant
Create a secure partner data exchange: quotas, cost limits, auditing, and revocation.
We are going to design a secure partner data exchange system. Requirements:
We assume we are building an API for partners to exchange data. The system should:
Steps:
Define the data model:
We assume we have an API gateway or middleware that intercepts every request.
Process for each request: a. Authenticate the partner (via API key, etc.) b. Check if the partner is active (not revoked). c. Check quotas: - For the given partner and the current period (e.g., today for daily), check if the current_usage + requested_data_in (or out) exceeds the limit. - We may have to update the current_usage and reset if the period has changed. d. Check cost limit: - Calculate the cost of the current request (maybe based on data volume or a fixed cost per request). - Check if current_cost + request_cost exceeds the limit for the current period. - Update current_cost and reset if the period has changed. e. If all checks pass, process the request and then: - Update the usage and cost in the quotas and cost limits. - Create an audit log entry. f. If any check fails, reject the request and log the attempt.
Revocation: an admin can revoke a partner by setting their status to 'revoked'. This will prevent future requests.
We also need a way to reset quotas and cost limits periodically (e.g., at midnight for daily, first of the month for monthly). This can be done by a cron job or by checking on each request (if the reset_time has passed, reset the current_usage and current_cost to 0 and set a new reset_time).
We must consider concurrency: multiple requests at the same time for the same partner might try to update the same quota. We need to use database transactions or atomic operations to avoid over-usage.
Implementation considerations:
Let's sketch the tables:
Table: partners id (primary key) name status (enum: 'active', 'revoked') api_key (unique)
Table: quotas id (primary key) partner_id (foreign key to partners.id) quota_type (string, e.g., 'daily_in', 'monthly_out') limit_value (numeric, the maximum allowed in the period) current_usage (numeric, default 0) reset_time (timestamp, when the current period ends and we reset)
Table: cost_limits id (primary key) partner_id (foreign key to partners.id) limit_value (numeric, in dollars) current_cost (numeric, default 0) reset_time (timestamp)
Table: audit_logs id (primary key) partner_id (foreign key) timestamp (default now) action (string) data_in (numeric, bytes or units) data_out (numeric) cost (numeric) status (string, e.g., 'success', 'quota_exceeded', 'cost_exceeded', 'revoked') details (jsonb, for extra info)
Request comes in with an API key.
Step 1: Find partner by api_key. If not found, return 401. Step 2: Check partner.status. If 'revoked', return 403 and log. Step 3: For each quota that applies to this request (e.g., we are sending data out, so check 'out' quotas), do: - Lock the quota row for update (to prevent concurrent updates from overusing). - Check if the current period has expired (reset_time < now). If so, reset current_usage to 0 and set a new reset_time (e.g., for daily, add 1 day; for monthly, add 1 month). - Check if current_usage + requested_data_out <= limit_value. If not, reject and log. - If okay, then later (after processing the request) we will update current_usage.
Step 4: Similarly for cost_limits: - Lock the cost_limit row for update. - Check reset and reset if needed. - Calculate the cost of the request (we need a cost function, which might be based on data volume or fixed per request). - Check if current_cost + request_cost <= limit_value. If not, reject and log.
Step 5: If all checks pass, process the request (exchange data).
Step 6: Update the quotas and cost_limits with the new usage and cost.
Step 7: Create an audit_log entry with success.
Cost calculation: We need a way to assign a cost to a request. This could be:
We also might have different quotas for different endpoints or data types. However, for simplicity, we assume the quotas are for the entire partner (all endpoints) and for data in/out.
We might also want to have a way to exempt certain partners from quotas or have different cost structures. This can be done by having multiple quota and cost_limit records per partner, and then we check the ones that are applicable.
Alternatively, we can have a more flexible model where we define quota and cost rules by partner and by endpoint. But the requirement is for partner data exchange, so we keep it simple.
We must also consider that a partner might have both a daily and monthly quota. We need to check all applicable quotas.
Implementation in code (pseudo-code):
function handle_request(partner_id, data_in, data_out, endpoint): // Step 1: Get partner and check status partner = Partner.get(partner_id) if not partner or partner.status != 'active': log_audit(partner_id, action, data_in, data_out, 0, 'revoked' if partner and partner.status=='revoked' else 'unauthorized') return error
// Step 2: Get all quotas for this partner that are of type relevant to this request (e.g., if data_out>0, then we need to check 'out' quotas)
quotas = Quota.where(partner_id=partner_id).lock_for_update().all()
for quota in quotas:
if (quota.quota_type ends with '_out' and data_out>0) or (quota.quota_type ends with '_in' and data_in>0):
// Check and reset if needed
if quota.reset_time < now:
quota.current_usage = 0
quota.reset_time = calculate_next_reset(quota.quota_type) // e.g., for daily, next day at midnight; for monthly, next month 1st.
quota.save()
// Check limit
if quota.current_usage + (quota.quota_type ends with '_out' ? data_out : data_in) > quota.limit_value:
log_audit(partner_id, action, data_in, data_out, 0, 'quota_exceeded', details={quota_id: quota.id})
return error
// Step 3: Cost limit
cost_limit = CostLimit.where(partner_id=partner_id).lock_for_update().first()
if cost_limit:
if cost_limit.reset_time < now:
cost_limit.current_cost = 0
cost_limit.reset_time = calculate_next_reset_for_cost() // maybe same as monthly quota?
cost_limit.save()
request_cost = calculate_cost(data_in, data_out, endpoint) // implement this
if cost_limit.current_cost + request_cost > cost_limit.limit_value:
log_audit(partner_id, action, data_in, data_out, request_cost, 'cost_exceeded')
return error
// Step 4: Process the request (exchange data)
success = true
try:
// ... actual data exchange ...
except:
success = false
// Step 5: Update quotas and cost if success
if success:
for quota in quotas:
if (quota.quota_type ends with '_out' and data_out>0) or (quota.quota_type ends with '_in' and data_in>0):
quota.current_usage += (quota.quota_type ends with '_out' ? data_out : data_in)
quota.save()
if cost_limit:
cost_limit.current_cost += request_cost
cost_limit.save()
// Step 6: Audit
log_audit(partner_id, action, data_in, data_out, request_cost, success ? 'success' : 'failure')
Let me know if you have any questions or if you want to adjust any part. I'll design a comprehensive Secure Partner Data Exchange System with quotas, cost limits, auditing, and revocation capabilities. Here's a complete architecture:
Partner Management:
- Partner Registry
- Credential Store (API keys, OAuth tokens)
- Status Management (active/suspended/revoked)
Quota & Limit Engine:
- Multi-dimensional quotas (by time, data volume, API calls)
- Cost tracking & limits (monetary/resource-based)
- Real-time enforcement
Auditing & Compliance:
- Immutable audit logs
- Compliance reporting
- Anomaly detection
Revocation & Security:
- Instant access revocation
- Key rotation
- Security incident response
-- Partners table
CREATE TABLE partners (
id UUID PRIMARY KEY,
name VARCHAR(255) NOT NULL,
status VARCHAR(50) DEFAULT 'active', -- active, suspended, revoked
api_key_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
revoked_at TIMESTAMP,
revocation_reason TEXT
);
-- Quotas (multi-dimensional)
CREATE TABLE quotas (
id UUID PRIMARY KEY,
partner_id UUID REFERENCES partners(id),
quota_type VARCHAR(50), -- 'daily', 'monthly', 'total'
scope VARCHAR(50), -- 'api_calls', 'data_in', 'data_out', 'storage'
limit_value BIGINT NOT NULL,
current_usage BIGINT DEFAULT 0,
reset_period VARCHAR(20), -- 'daily', 'monthly', 'never'
last_reset TIMESTAMP,
UNIQUE(partner_id, quota_type, scope, reset_period)
);
-- Cost limits
CREATE TABLE cost_limits (
id UUID PRIMARY KEY,
partner_id UUID REFERENCES partners(id),
cost_type VARCHAR(50), -- 'monetary', 'compute_units', 'api_credits'
limit_value DECIMAL(20,2) NOT NULL,
current_cost DECIMAL(20,2) DEFAULT 0,
currency VARCHAR(3) DEFAULT 'USD',
reset_period VARCHAR(20),
last_reset TIMESTAMP,
UNIQUE(partner_id, cost_type, reset_period)
);
-- Audit log (immutable)
CREATE TABLE audit_logs (
id UUID PRIMARY KEY,
partner_id UUID REFERENCES partners(id),
timestamp TIMESTAMP DEFAULT NOW(),
action VARCHAR(100) NOT NULL, -- 'api_call', 'quota_check', 'revoke', etc.
endpoint VARCHAR(255),
method VARCHAR(10),
request_size BIGINT,
response_size BIGINT,
cost_incurred DECIMAL(20,2),
quota_before JSONB,
quota_after JSONB,
status VARCHAR(50), -- 'success', 'quota_exceeded', 'cost_exceeded', 'rate_limited'
ip_address INET,
user_agent TEXT,
metadata JSONB
) PARTITION BY RANGE (timestamp);
-- Revocation events
CREATE TABLE revocation_events (
id UUID PRIMARY KEY,
partner_id UUID REFERENCES partners(id),
revoked_by UUID, -- admin user ID
reason VARCHAR(255),
revoked_at TIMESTAMP DEFAULT NOW(),
effects JSONB -- what was revoked: ['api_access', 'data_read', 'data_write']
);
-- Rate limiting (sliding window)
CREATE TABLE rate_limit_counters (
partner_id UUID REFERENCES partners(id),
window_start TIMESTAMP,
request_count INTEGER DEFAULT 0,
PRIMARY KEY (partner_id, window_start)
);
# Middleware that runs on every request
def authenticate_and_enforce(request):
partner = verify_api_key(request.headers['X-API-Key'])
if partner.status != 'active':
raise PermissionDenied("Partner account not active")
# Check rate limiting (sliding window)
if check_rate_limit(partner.id):
raise RateLimitExceeded()
# Check quotas and costs
enforce_quotas_and_limits(partner, request)
# Log the request
log_audit_event(partner, request, 'api_call_start')
return partner
def enforce_quotas_and_limits(partner, request):
"""Check all applicable quotas and costs before processing"""
# Get all active quotas for partner
active_quotas = get_active_quotas(partner.id)
for quota in active_quotas:
# Reset if period expired
if should_reset_quota(quota):
reset_quota(quota)
# Calculate usage for this request
usage = calculate_usage(request, quota.scope)
if quota.current_usage + usage > quota.limit_value:
log_audit_event(partner, request, 'quota_exceeded',
{'quota_id': quota.id, 'limit': quota.limit_value})
raise QuotaExceeded(f"Quota exceeded for {quota.scope}")
# Check cost limits
total_cost = calculate_request_cost(request)
active_cost_limits = get_active_cost_limits(partner.id)
for cost_limit in active_cost_limits:
if should_reset_cost(cost_limit):
reset_cost_limit(cost_limit)
if cost_limit.current_cost + total_cost > cost_limit.limit_value:
log_audit_event(partner, request, 'cost_exceeded',
{'cost_limit_id': cost_limit.id, 'limit': cost_limit.limit_value})
raise CostLimitExceeded(f"Cost limit exceeded: {cost_limit.cost_type}")
class RevocationManager:
@staticmethod
def revoke_partner(partner_id, revoked_by, reason, effects=None):
"""Instant revocation with cascading effects"""
with transaction.atomic():
# 1. Update partner status
partner = Partner.objects.get(id=partner_id)
partner.status = 'revoked'
partner.revoked_at = timezone.now()
partner.revocation_reason = reason
partner.save()
# 2. Log revocation event
RevocationEvent.objects.create(
partner_id=partner_id,
revoked_by=revoked_by,
reason=reason,
effects=effects or ['api_access']
)
# 3. Invalidate all active sessions/tokens
invalidate_sessions(partner_id)
# 4. Clear Redis caches
cache.delete_many([
f'partner_quota:{partner_id}:*',
f'partner_cost:{partner_id}:*',
f'partner_session:{partner_id}'
])
# 5. Notify monitoring systems
send_revocation_alert(partner, reason)
# 6. Force logout all active connections
terminate_active_connections(partner_id)
class AuditLogger:
@staticmethod
def log_event(partner_id, action, request, status, **kwargs):
"""Immutable logging with context"""
log_entry = AuditLog(
partner_id=partner_id,
action=action,
timestamp=timezone.now(),
endpoint=request.path,
method=request.method,
ip_address=get_client_ip(request),
user_agent=request.META.get('HTTP_USER_AGENT', ''),
status=status,
metadata={
'query_params': dict(request.GET),
'headers': dict(request.headers),
**kwargs
}
)
# Capture request/response sizes
if hasattr(request, 'body'):
log_entry.request_size = len(request.body)
log_entry.save()
# Also send to SIEM/log aggregation
send_to_siem(log_entry)
return log_entry
# Celery periodic task
@app.task
def reset_expired_quotas():
"""Reset quotas and costs that have exceeded their reset period"""
now = timezone.now()
# Reset quotas
expired_quotas = Quota.objects.filter(
reset_period__isnull=False,
last_reset__lt=now - get_reset_timedelta(F('reset_period'))
)
for quota in expired_quotas:
quota.current_usage = 0
quota.last_reset = now
quota.save()
# Reset cost limits
expired_costs = CostLimit.objects.filter(
reset_period__isnull=False,
last_reset__lt=now - get_reset_timedelta(F('reset_period'))
)
for cost_limit in expired_costs:
cost_limit.current_cost = 0
cost_limit.last_reset = now
cost_limit.save()
# Sample partner configuration
partner_abc:
quotas:
- type: daily
scope: api_calls
limit: 10000 # calls per day
- type: monthly
scope: data_out
limit: 1073741824 # 1GB per month
- type: total
scope: storage
limit: 5368709120 # 5GB total storage
cost_limits:
- type: monetary
limit: 100.00 # $100 per month
currency: USD
reset_period: monthly
- type: compute_units
limit: 1000 # compute units per day
reset_period: daily
rate_limits:
- requests_per_second: 10
burst: 20
permissions:
- endpoint: /api/v1/data/*
methods: [GET, POST]
scopes: [read:data, write:data]
Secret Management:
Data Validation:
def validate_quota_adjustment(partner_id, adjustment):
"""Ensure quota adjustments are within safe bounds"""
MAX_DAILY_INCREASE = 1000 # max % increase per day
current = get_current_quota(partner_id)
if adjustment / current > MAX_DAILY_INCREASE / 100:
raise ValidationError("Quota increase too large")
Audit Trail Integrity:
Time Window Attacks:
class Monitoring:
@staticmethod
def check_partner_health():
alerts = []
# Check near-limit usage
near_limit_partners = Partner.objects.filter(
quotas__current_usage__gte=F('quotas__limit_value') * 0.8
).distinct()
for partner in near_limit_partners:
alerts.append({
'partner': partner.name,
'type': 'quota_80_percent',
'severity': 'warning'
})
# Check sudden usage spikes
spike_detected = detect_usage_spike(partner_id)
if spike_detected:
alerts.append({
'partner': partner.name,
'type': 'usage_spike',
'severity': 'critical'
})
return alerts
# Partner self-service
GET /api/v1/partner/quotas # View current usage
POST /api/v1/partner/quotas/request # Request quota increase
GET /api/v1/partner/costs # View cost breakdown
# Admin endpoints (RBAC protected)
POST /admin/partners/{id}/revoke # Revoke partner
PUT /admin/partners/{id}/quotas # Adjust quotas
PUT /admin/partners/{id}/cost-limits # Adjust cost limits
GET /admin/audit?partner={id}&date=2024-01-01 # Audit reports
This design provides:
Would you like me to elaborate on any specific component (e.g., the exact Redis implementation for rate limiting, the audit log schema for specific compliance frameworks, or the revocation propagation mechanism)?
We must also consider that the same partner might have multiple concurrent requests. We are using row-level locking on the quota and cost_limit rows, so that only one transaction can update at a time for a given partner's quota. This might become a bottleneck. We can try to minimize the time we hold the lock by doing the check and then the update, but we must hold the lock until we update to avoid race conditions.
Alternatively, we can use a more scalable approach by having a separate service for quota and cost tracking that uses a distributed lock or a queue. But for simplicity, we assume the load is not extremely high.
Revocation: we can set the partner's status to 'revoked'. Then in step 1, we reject.
We also need to consider that the audit log should be written even if the request fails (for security and compliance).
We might also want to have a way to adjust quotas and cost limits (e.g., increase limit, reset manually) for a partner.
We should also consider that the data_in and data_out might be in different units (bytes, records, etc.). We assume the unit is consistent (e.g., bytes) and the quotas are in the same unit.
The reset_time calculation: For daily: reset at midnight UTC? or at the start of the day in the partner's timezone? We might need to store the partner's timezone. But for simplicity, we can use UTC and reset at 00:00 UTC.
We can store the reset_time as the end of the current period. For example, for daily, reset_time is today at 23:59:59 UTC? Actually, it's easier to store the start of the next period. So if today is 2023-10-05, then the reset_time for daily would be 2023-10-06 00:00:00. Then when we check and the current time is >= reset_time, we reset and set reset_time to the next day.
Similarly for monthly: reset_time is the first day of the next month at 00:00:00.
We can have a helper function that, given a quota_type, returns the next reset_time.
Also, we might have a quota that is not time-based (e.g., total lifetime quota). Then we never reset. We can handle that by having reset_time as NULL and then we don't reset.
We must also consider that a partner might have multiple quotas of the same type? Probably not, but if they do, we should sum the limits? Or we should enforce only one quota per type per partner? Let's assume one quota per type per partner.
We can also have a default quota for new partners.
We must also think about the cost calculation: it might be complex and depend on the endpoint and the data volume. We can have a table of cost_rules:
Table: cost_rules id endpoint_pattern (regex or exact match) cost_per_unit (e.g., per MB) unit (e.g., 'MB', 'request')
Then, for a given request, we find the matching rule and calculate the cost.
Alternatively, the cost might be fixed per endpoint, or per partner. We can have:
cost_rules: partner_id (nullable, if set then only for that partner, else global) endpoint (or pattern) cost_type: 'fixed' or 'per_unit' value: if fixed, then the fixed cost; if per_unit, then the cost per unit.
Then, calculate_cost: rule = find_rule(partner_id, endpoint) if rule.cost_type == 'fixed': return rule.value else: // per_unit: we need to know the unit. We can have the rule specify the unit (e.g., 'MB') and then we convert the data_in and data_out to that unit? Or we can have the rule specify the unit and the data volume in that unit.
But note: the request has data_in and data_out. We might charge for data_in, data_out, or both? The rule should specify which.
Alternatively, we can have:
cost_rules: partner_id endpoint in_cost_per_unit (nullable) out_cost_per_unit (nullable) unit (the unit for the per_unit costs, e.g., 'MB')
Then, cost = (data_in in unit * in_cost_per_unit) + (data_out in unit * out_cost_per_unit)
But then if we have a fixed cost, we can set in_cost_per_unit and out_cost_per_unit to 0 and have a fixed_cost field? Or we can have:
cost_rules: partner_id endpoint fixed_cost (nullable) in_cost_per_unit (nullable) out_cost_per_unit (nullable) unit
Then, cost = fixed_cost (if set) + (in_cost_per_unit * data_in_in_unit) + (out_cost_per_unit * data_out_in_unit)
But note: if both fixed and per_unit are set, we add them.
However, we might also have a rule that only applies to data_in or only to data_out.
Alternatively, we can break it down:
We have cost components. For a given request, we can have multiple cost components (e.g., a fixed cost for using the API, plus a cost for data out).
So we can have:
cost_components:
id
partner_id (nullable)
endpoint (nullable, if null then applies to all endpoints for that partner)
type: 'fixed', 'per_in', 'per_out'
unit (for per_in and per_out, the unit, e.g., 'MB')
value (the cost)
Then for a request, we sum:
fixed: all fixed components for the partner and endpoint (or global if partner_id and endpoint match, or partner_id only, etc.)
per_in: for each per_in component, convert data_in to the component's unit and multiply by value.
per_out: similarly.
But this might be overkill.
Given the complexity, let's stick to a simple cost rule per partner and endpoint:
cost_rules: id partner_id (nullable, if null then global rule) endpoint (exact match or pattern? let's say exact for now) cost_type: 'fixed' or 'per_unit' unit (only for per_unit, e.g., 'MB') value (if fixed, then the fixed cost; if per_unit, then the cost per unit)
Then, for a request, we find the rule by: First, try to find a rule for the specific partner and endpoint. If not found, try to find a rule for the partner without endpoint (i.e., partner_id and endpoint is null). If not found, try to find a global rule (partner_id is null and endpoint is null or matches?).
But note: we might have multiple rules? We should design so that we have at most one rule per (partner, endpoint). We can enforce that with a unique constraint on (partner_id, endpoint) where partner_id and endpoint are not both null? Actually, we can have:
unique (partner_id, endpoint) where (partner_id is not null and endpoint is not null)
unique (partner_id) where (partner_id is not null and endpoint is null) -- partner-wide rule
unique (endpoint) where (partner_id is null and endpoint is not null) -- endpoint-specific global rule
and then the global rule (both null) only one.
Alternatively, we can have a priority system: partner-endpoint specific > partner-wide > endpoint-specific global > global.
But for simplicity, let's assume we have one rule per partner (if any) and if not, a global rule. And the rule applies to all endpoints for that partner? Then we don't need endpoint in the rule.
Actually, the requirement is for partner data exchange, so maybe the cost is per partner, not per endpoint.
Let's simplify:
We have a cost_limit per partner, and we calculate the cost of a request by a fixed formula:
cost = (data_in + data_out) * cost_per_unit
And we have a cost_per_unit set per partner? or global?
We can store the cost_per_unit in the partner table? Or in a separate configuration.
Given the time, let's go with:
Each partner has a cost_per_unit (in $/MB). If not set, use a global default.
Then, the cost of a request is: (data_in + data_out) in MB * cost_per_unit.
And we track the cost in the cost_limits table.
Given the above, we adjust:
Table: partners ... cost_per_unit (numeric, default from global config)
But then we have a global config for default cost_per_unit.
Alternatively, we can have:
Table: cost_config
id
partner_id (nullable)
cost_per_unit (numeric)
Then for a partner, we use the partner-specific cost_per_unit if exists, else the global (partner_id null).
But again, we are simplifying.
Let's stick to:
partners table has a field: cost_per_unit.
Then, in the code:
request_cost = (data_in + data_out) * partner.cost_per_unit
But note: data_in and data_out are in bytes? We need to convert to the unit of cost_per_unit (e.g., per MB). So:
request_cost = ( (data_in + data_out) / (1024*1024) ) * partner.cost_per_unit
However, we must be consistent with the quota units. The quotas are in the same unit as data_in and data_out (bytes). So the quota limit is in bytes.
But the cost_per_unit is per MB. So we convert bytes to MB.
Alternatively, we can store the quotas and cost in the same unit? But the cost is in dollars, so that's different.
So, in summary:
Quotas: in bytes (or whatever unit we use for data_in and data_out). Cost: in dollars, calculated by converting data_in and data_out to MB (or whatever unit we define for cost_per_unit) and multiplying by cost_per_unit.
We must also consider that the cost_per_unit might be 0 for some partners (free). That's okay.
Now, let's write the pseudo-code again with the above:
function handle_request(partner_id, data_in, data_out, endpoint): partner = Partner.get(partner_id) if not partner or partner.status != 'active': log_audit(...) return error
// We assume data_in and data_out are in bytes.
// Check quotas
quotas = Quota.where(partner_id=partner_id).lock_for_update().all()
for quota in quotas:
// Determine if this quota applies to the current request.
// We assume the quota.quota_type is either 'daily_in', 'daily_out', 'monthly_in', 'monthly_out', etc.
// We'll check the direction (in/out) and the period.
direction = quota.quota_type.split('_')[1] // 'in' or 'out'
period = quota.quota_type.split('_')[0] // 'daily' or 'monthly'
// If the request has data in the direction of the quota, then check.
if (direction == 'in' and data_in > 0) or (direction == 'out' and data_out > 0):
// Reset if needed
if quota.reset_time < now:
quota.current_usage = 0
quota.reset_time = calculate_next_reset(period) // returns the next reset time for the given period (in UTC)
quota.save()
// The usage to add
usage_to_add = (direction == 'in') ? data_in : data_out
if quota.current_usage + usage_to_add > quota.limit_value:
log_audit(partner_id, 'data_exchange', data_in, data_out, 0, 'quota_exceeded', {quota_id: quota.id})
return error
// Check cost limit
cost_limit = CostLimit.where(partner_id=partner_id).lock_for_update().first()
if cost_limit:
if cost_limit.reset_time < now:
cost_limit.current_cost = 0
cost_limit.reset_time = calculate_next_reset_for_cost() // maybe monthly? We can have a cost_limit period (e.g., monthly). We can store the period in the cost_limits table? Or assume it's monthly.
cost_limit.save()
// Calculate request cost in dollars.
// Convert bytes to MB: (data_in + data_out) / (1024*1024)
data_total_mb = (data_in + data_out) / (1024.0 * 1024.0)
request_cost = data_total_mb * partner.cost_per_unit
if cost_limit.current_cost + request_cost > cost_limit.limit_value:
log_audit(partner_id, 'data_exchange', data_in, data_out, request_cost, 'cost_exceeded')
return error
// Process the request (exchange data)
success = true
try:
// ... actual data exchange ...
except:
success = false
// Update quotas and cost if success
if success:
for quota in quotas:
direction = quota.quota_type.split('_')[1]
if (direction == 'in' and data_in > 0) or (direction == 'out' and data_out > 0):
usage_to_add = (direction == 'in') ? data_in : data_out
quota.current_usage += usage_to_add
quota.save()
if cost_limit:
cost_limit.current_cost += request_cost
cost_limit.save()
// Audit
log_audit(partner_id, 'data_exchange', data_in, data_out, request_cost, success ? 'success' : 'failure')
We must also consider that the same partner might have multiple quotas and cost limits for different periods. We are checking all of them.
The function calculate_next_reset(period): if period == 'daily': // next reset is tomorrow at 00:00:00 UTC now = datetime.utcnow() next_reset = datetime(now.year, now.month, now.day) + timedelta(days=1) elif period == 'monthly': // next reset is the first day of next month at 00:00:00 UTC now = datetime.utcnow() if now.month == 12: next_reset = datetime(now.year+1, 1, 1) else: next_reset = datetime(now.year, now.month+1, 1) else: // for non-time-based, we don't reset? Then we don't change reset_time? But then we never reset. // So for non-time-based, we don't do the reset check? We can have a flag in the quota table for whether it's time-based. // Alternatively, we can store the period as null for non-time-based and then skip reset.
But in our model, we have a reset_time. For non-time-based, we can set reset_time to a distant future (like '9999-12-31') and then never reset.
Alternatively, we can have a boolean field in the quota: is_time_based. If false, then we don't reset.
Let's change the reset logic:
if quota.is_time_based and quota.reset_time < now:
reset...
But to keep it simple, we assume all quotas are time-based. If we want a lifetime quota, we set the reset_time to a very far future and the limit is the lifetime limit.
So we can set the reset_time for a lifetime quota to, say, 2099-12-31. Then it will never reset.
Similarly for cost_limit.
We also need to consider that the reset_time might be in the past by a long time (if the system was down). We reset and then set the next reset.
We must also consider that the current_usage might be above the limit if we reset and then immediately get a huge request? But that's okay because we reset to 0 and then check the new request.
But what if we have a quota that is not reset automatically (like lifetime) and we want to reset it manually? We can have an admin function to reset the current_usage to 0 and set a new reset_time.
Now, let's think about the audit log: we are logging every request, even if it fails. We are also logging the cost (if calculated) and the reason for failure.
We also need to log the admin actions (like revocation, resetting quotas, etc.) in the audit log? We can have a separate table for admin actions, or we can use the same audit_log with a different action (e.g., 'partner_revoked', 'quota_reset').
We can extend the audit_log to have an actor field (who performed the action) and an action field that can be 'api_request', 'admin_revoke', etc.
But for the API requests, the actor is the partner. For admin actions, the actor is the admin user.
We can change the audit_log table:
audit_logs: id timestamp actor_type (enum: 'partner', 'admin') actor_id (if partner, then partner_id; if admin, then admin user id) action (string, e.g., 'data_exchange', 'partner_revoked', 'quota_reset') partner_id (for admin actions, we still want to know which partner was affected) data_in, data_out, cost (for data_exchange) status (for data_exchange: success/failure; for admin actions, maybe 'completed') details (jsonb)
Then, for an API request: actor_type = 'partner' actor_id = partner_id action = 'data_exchange' partner_id = partner_id (same as actor_id) data_in, data_out, cost as above status = 'success' or failure reason
For admin revoking a partner: actor_type = 'admin' actor_id = admin_user_id action = 'partner_revoked' partner_id = the partner being revoked status = 'completed'
This way, we have a unified audit log.
Now, let's adjust the code for the audit log.
We also need to consider that the request might not have data_in or data_out? But in our model, we are exchanging data, so we assume there is at least one.
We must also consider that the same request might be retried? We might want to idempotent requests? But that's a separate concern.
We assume that each request is unique and we log every attempt.
Now, let's consider the concurrency again: we are locking the quota and cost_limit rows for the partner. This means that for a given partner, all requests are serialized. If a partner has many concurrent requests, this will be a bottleneck.
We can try to minimize the lock time by:
Doing the checks and updates in a single transaction, but we are already doing that.
We can try to do the checks without locking and then update with a condition that the current_usage hasn't changed? But that's prone to race conditions.
Alternatively, we can use a more scalable approach:
We can store the current_usage and reset_time in a cache (like Redis) and update atomically. Then periodically sync to the database.
But for simplicity and strong consistency, we use database locks.
We can also consider having separate rows for each quota period. For example, for daily quota, we have a row for each day. Then we don't need to reset, we just create a new row for the new day. But then we have to manage many rows.
Alternatively, we can have:
quotas:
id
partner_id
period (e.g., 'daily', 'monthly')
direction ('in', 'out')
limit_value
current_usage
period_start (date, the start of the current period, e.g., 2023-10-05 for daily)
period_end (date, the end of the current period, e.g., 2023-10-06 for daily)
Then, when we get a request, we find the quota row for the current period (period_start <= today < period_end). If not found, we create a new one for the current period.
This way, we don't need to reset the same row; we just create new rows for each period. But then we have to check the current period's row and update it.
This avoids the reset_time and the reset logic. We just find the current period's row.
But then we have to manage the creation of new rows for each period. We can do that on the fly when we don't find a row for the current period.
And for lifetime quota, we can have period='lifetime' and then we don't create new rows.
This is a common pattern for time-series data.
Let's change the quotas table:
quotas:
id
partner_id
period (enum: 'daily', 'monthly', 'lifetime')
direction (enum: 'in', 'out')
limit_value
current_usage
period_start (date, for daily and monthly, the start of the period; for lifetime, maybe null or the date when the partner was created)
period_end (date, for daily and monthly, the end of the period; for lifetime, null)
Then, for a given partner and a given period and direction, we want the row for the current period.
How to define the current period for daily?
For daily: period_start = today (UTC) and period_end = tomorrow (UTC). But note: we might want to reset at midnight UTC.
We can compute the current period_start and period_end for the request's time (we assume the request time is now).
For daily:
period_start = date(now) // today at 00:00:00 UTC
period_end = period_start + 1 day
For monthly:
period_start = date(now.year, now.month, 1)
period_end = period_start + 1 month (but careful with variable month lengths)
Then, we look for a quota row with:
partner_id = ?
period = ?
direction = ?
period_start = ? and period_end = ?
If not found, we create a new one with current_usage=0 and the given period_start and period_end.
Then we check and update.
This way, we don't need to reset the same row; we just create a new row for each period. And we can have multiple rows for the same partner and period/direction but for different periods.
But note: we might have a quota that is not time-based (lifetime). Then we have period='lifetime' and we don't create new rows. We just use the one row.
This model is more scalable because we don't have to update the same row repeatedly. We are creating a new row per period, and then we update that row for the requests in that period.
But then we have to manage the creation of new rows. We can do:
SELECT * FROM quotas
WHERE partner_id = ?
AND period = ?
AND direction = ?
AND period_start <= ?
AND period_end > ?
FOR UPDATE
If not found, then create a new row for the current period.
Then we update the current_usage.
This way, we are locking the row for the current period, which is different for each day/month, so we have less contention.
However, for the same period, we still have contention if there are many requests in the same day for the same partner and direction.
But that's unavoidable because we are tracking a single counter for the day.
So we are still serializing requests for the same partner, same direction, same period.
But if a partner has multiple directions (in and out) then they are on different rows, so less contention.
Also, if we have multiple periods (daily and monthly) then they are on different rows.
So this is better.
Let's adjust the quota table to this model.
Similarly for cost_limits? We can do the same: have a cost_limits table with period (daily, monthly, lifetime) and then we have a row per period.
But note: the cost is not direction-specific. So we don't have direction.
cost_limits: id partner_id period (daily, monthly, lifetime) limit_value current_cost period_start period_end
Then we find the current period's row.
Now, the code for quotas:
// For each quota that applies (we have a list of (period, direction) that we need to check for this request? // But now we don't have a fixed set of quotas per partner. Instead, we have a set of quota configurations (what periods and directions are tracked for a partner).
// We need to know which periods and directions to check. We can have a table that defines the quota configurations for a partner:
quota_configs:
id
partner_id
period (daily, monthly, lifetime)
direction (in, out) // for lifetime, direction might be null? or we can have both? Let's say for lifetime, we can have two rows: one for in and one for out? Or we can have a row without direction?
// Alternatively, we can have the quota table itself define the configuration? But then we have multiple rows for the same configuration (different periods).
// We need to know which (period, direction) combinations to check for a given request.
// Let's have:
partner_quotas:
id
partner_id
period
direction
limit_value
Then, for each partner_quota row, we find the current period's usage row (in the quotas table) for that partner, period, and direction.
// So:
Step: Get all partner_quotas for the partner.
For each partner_quota:
period = partner_quota.period
direction = partner_quota.direction
// Compute current period_start and period_end for the given period (if period is not lifetime, then we compute based on now; if lifetime, then period_start is the beginning of time and period_end is far future? But we don't have a row for lifetime? We can have one row for lifetime with period_start = '1970-01-01' and period_end = '9999-12-31').
// Then, find the usage row in quotas table for:
partner_id, period, direction, period_start, period_end.
If not found, create it with current_usage=0.
Then check if current_usage + (direction=='in'?data_in:data_out) > partner_quota.limit_value.
// But note: the partner_quota.limit_value is the limit for that period and direction.
// So we have:
Table: partner_quotas
id
partner_id
period (daily, monthly, lifetime)
direction (in, out) // for lifetime, we can have two rows: one for in and one for out? Or we can have a row with direction='both'? Let's keep it simple: for lifetime, we can have two rows if we want to track in and out separately? But the requirement is for partner data exchange, so we might want to track both separately even for lifetime.
But if we want a lifetime quota for total data (in+out) then we need a row without direction?
Alternatively, we can have:
partner_quotas:
id
partner_id
period
direction (nullable, if null then it applies to both? but then we have to decide how to check: if we have a row with direction=null and period=daily, then we check the sum of data_in and data_out?
This is getting complex.
Let's stick to:
For each partner, we can have multiple quota configurations, each with a period and a direction (in or out). And we check each one independently.
For example, a partner can have:
daily in: 100 MB
daily out: 200 MB
monthly in: 1000 MB
monthly out: 2000 MB
lifetime in: 10000 MB
lifetime out: 20000 MB
Then, for a request with data_in=50 MB and data_out=100 MB, we check:
daily in: current_usage_in + 50 <= 100?
daily out: current_usage_out + 100 <= 200?
monthly in: current_usage_in + 50 <= 1000?
monthly out: current_usage_out + 100 <= 2000?
lifetime in: current_usage_in + 50 <= 10000?
lifetime out: current_usage_out + 100 <= 20000?
So we have 6 checks.
We don't have a quota that is for the sum of in and out. If we want that, we can have a row with direction='total'? But then we have to define how we calculate the usage for that row.
Alternatively, we can have a separate row for the sum? But then we are duplicating data.
Given the complexity, let's not support a quota for the sum. We only support in and out separately.
If the business requires a quota for the sum, we can have two rows and then the admin must set both to the same limit? Not ideal.
Alternatively, we can have:
partner_quotas:
id
partner_id
period
direction (in, out, or 'both') // if 'both', then we use the sum of in and out for this quota.
Then, when checking:
if direction == 'in':
usage = data_in
else if direction == 'out':
usage = data_out
else: // both
usage = data_in + data_out
But then we have to be careful because we are updating the same usage row for both in and out? No, the usage row is per (period, direction). So for direction='both', we have a usage row that tracks the sum.
And we have to update that usage row with the sum of in and out.
But then we are tracking the same data in two different rows? For example, if we have a daily in and a daily both, then the same data_in is counted in both.
That might be intended? Or not.
Let's avoid that and say that we only have in and out separately. If we want a quota for the sum, we can have a separate row with direction='both' and then we don't have separate in and out rows? But then we lose the ability to track in and out separately.
Alternatively, we can have:
We have a usage row for each (period, direction) and then we also have a usage row for (period, 'both') that is the sum of in and out? But then we are storing redundant data and we have to update multiple rows.
Given the time, let's stick to only in and out separately. We can always add a 'both' direction later.
So, we have:
partner_quotas: id partner_id period (daily, monthly, lifetime) direction (in, out) limit_value
And then we have the usage table (quotas) that has:
id
partner_id
period
direction
period_start
period_end
current_usage
And we have a unique constraint on (partner_id, period, direction, period_start, period_end) so that for a given partner, period, direction, and period (the time period) we have at most one row.
Now, the code for checking quotas:
// Get all quota configs for the partner configs = PartnerQuota.where(partner_id=partner_id).all()
for config in configs: period = config.period direction = config.direction
// Compute period_start and period_end for now and the given period.
period_start, period_end = compute_period(period, now)
// Find the usage row for this partner, period, direction, period_start, period_end.
// We lock it for update.
usage = Quota.where(partner_id=partner_id, period=period, direction=direction, period_start=period_start, period_end=period_end).lock_for_update().first()
if not usage:
// Create a new usage row for this period.
usage = Quota.create(partner_id=partner_id, period=period, direction=direction, period_start=period_start, period_end=period_end, current_usage=0)
// Determine the usage to add for this direction.
if direction == 'in':
add = data_in
else: // out
add = data_out
if usage.current_usage + add > config.limit_value:
log_audit(...)
return error
// Then, after processing, we update the usage rows for the ones that passed.
But note: we are locking the usage rows one by one. We must lock all the ones we are going to update before we process the request? Because if we lock one, then another request for the same partner might lock another one and then they both pass the check and then we update, and we might exceed the limit.
Example: Request1: locks daily_in row, checks, then processes. Request2: locks daily_out row, checks, then processes. Then both update and we might exceed both limits? But they are different directions, so that's okay.
But if we have two quotas for the same period and direction? We don't, because we have one config per (period, direction). So we are safe.
However, if we have a config for daily_in and another for daily_in (duplicate) then we would have two rows? We should enforce uniqueness in partner_quotas: (partner_id, period, direction) unique.
So we are safe.
But we are locking multiple rows. We must lock them in a consistent order to avoid deadlocks.
We can lock by the id of the usage row? But we don't know the id until we find or create the row.
Alternatively, we can lock by the (partner_id, period, direction, period_start, period_end) but we don't have the row until we create it.
We can do:
First, for all configs, compute the period_start and period_end. Then sort by (period, direction) to lock in a consistent order.
Then for each config in sorted order, find or create the usage row and lock it.
But if we create a row, we are inserting and then locking? We can do:
SELECT ... FOR UPDATE SKIP LOCKED? But we are creating if not exists.
Alternatively, we can use advisory locks? Or we can lock the partner row first?
Another idea: we can lock the partner row at the beginning? Then we are sure that only one request per partner is processed at a time? But that would be a big bottleneck.
We want to allow concurrent requests for the same partner as long as they are for different quotas? But if they are for the same quota (same period and direction) then we want to serialize them. But if they are for different quotas, we can allow concurrency.
So we want to lock only the usage rows that we are going to update.
But if we have two requests that both need to update the same usage row (same period and direction) then they will both try to lock that row and one will wait. That's okay.
But if they are for different usage rows, then they can proceed in parallel.
So we can do:
Step 1: For each config, compute the period_start and period_end.
Step 2: For each config, in a sorted order (by period, direction) do:
usage = Quota.where(...).lock_for_update().first()
if not usage:
// We have to create the row. But we cannot create it while holding a lock on another row? We are not holding any lock at this point? We are locking each row one by one.
// But if two requests try to create the same row at the same time? We might get a duplicate key error? Because we have a unique constraint on (partner_id, period, direction, period_start, period_end). So one will succeed and the other will fail. Then the one that fails can retry? Or we can catch the exception and then re-fetch.
// Alternatively, we can use INSERT ... ON CONFLICT DO NOTHING and then re-fetch.
This is getting complex.
Given the complexity, and since we expect that for a given partner and period and direction, there will be only one row, we can do:
We lock the partner row? Then we are sure that only one request per partner is processed at a time. But that's a bottleneck.
Alternatively, we can use a distributed lock per (partner_id, period, direction). But that's overkill.
Let's stick to locking the usage rows in a consistent order and handle the creation of new rows with a retry on duplicate key.
Steps:
sort the configs by (period, direction) // we can sort by period (daily, monthly, lifetime) and then direction.
for config in sorted_configs:
period_start, period_end = compute_period(config.period, now)
try:
usage = Quota.where(partner_id=partner_id, period=config.period, direction=config.direction, period_start=period_start, period_end=period_end).lock_for_update().first()
if not usage:
// Try to create
usage = Quota.create(partner_id=partner_id, period=config.period, direction=config.direction, period_start=period_start, period_end=period_end, current_usage=0)
except UniqueViolation:
// Another transaction created it, so fetch again.
usage = Quota.where(partner_id=partner_id, period=config.period, direction=config.direction, period_start=period_start, period_end=period_end).lock_for_update().first()
// Now we have the usage row locked.
// Check the limit.
Then, after processing, we update the usage rows.
But note: we are holding multiple locks at the same time? We are locking one row at a time, and then moving to the next. But we are not releasing the lock until the transaction ends. So we are holding all the locks for the usage rows that we found/created until the end.
That might be okay because the number of usage rows per request is small (at most 6: daily in/out, monthly in/out, lifetime in/out).
But if two requests for the same partner have different sets of configs? They will lock different rows and can proceed in parallel.
However, if they have the same set of configs, they will lock the same rows in the same order, so no deadlock.
So we are safe.
Similarly for cost_limits? We can have:
cost_limit_configs: id partner_id period (daily, monthly, lifetime)
Then we have a cost_limits table (usage) with:
id
partner_id
period
period_start
period_end
current_cost
And we do the same: for each cost_limit_config, find or create the current period's cost_limit row, lock it, check, and then update.
But note: the cost is not per direction. So we don't have direction.
And the cost calculation is the same for all cost limits? We calculate the request_cost once and then check against each cost_limit? But that doesn't make sense because we might have multiple cost limits (daily cost limit, monthly cost limit). We want to check each one independently.
So we calculate the request_cost once, and then for each cost_limit_config (period) we check:
if current_cost + request_cost > limit_value
But note: the request_cost is the same for all periods? Yes, because it's the cost of this request.
But then we are adding the same request_cost to multiple cost limits? That is intended because the request contributes to the daily cost, monthly cost, and lifetime cost.
So we do:
for each cost_limit_config:
find or create the cost_limit row for the current period (for that period).
lock it.
if current_cost + request_cost > config.limit_value -> error.
Then, if all pass, we update all the cost_limit rows with the request_cost.
But note: if we have a daily cost limit and a monthly cost limit, we are adding the same request_cost to both. That is correct because the request uses cost in both the daily and monthly periods.
However, what if we have a cost limit for the same period but multiple configs? We shouldn't have multiple cost_limit_configs for the same partner and period. So we enforce uniqueness on (partner_id, period) in cost_limit_configs.
Now, let's adjust the code for cost:
// Get all cost_limit_configs for the partner cost_configs = CostLimitConfig.where(partner_id=partner_id).all()
// If there are none, then we use the global cost limit? Or we don't have a cost limit? // We can have a global cost limit config (partner_id null) that applies to all partners that don't have a specific one.
But we can also have a default cost limit in the partners table? Let's not.
We can do:
If there are no cost_limit_configs for the partner, then we skip cost check? Or we use a global default?
The requirement says "cost limits", so we might not have a cost limit for every partner.
We can have:
cost_limit_configs:
id
partner_id (nullable, if null then it's a global config)
period
limit_value
Then, for a partner, we get:
specific = CostLimitConfig.where(partner_id=partner_id).all()
global = CostLimitConfig.where(partner_id=null).all()
all_configs = specific + global
But then we might have a global daily cost limit and a partner-specific monthly cost limit? That's okay.
Then we check all of them.
But note: the global config might not have a limit for every period? We can have:
global daily cost limit: $100
global monthly cost limit: $1000
And a partner might have only a monthly cost limit of $500? Then we check:
daily: global $100
monthly: partner $500 (overrides global? or we take the minimum? or we check both? We are checking all configs. So we would check both the global monthly and the partner monthly? That would be two checks for monthly? That doesn't make sense.
We want to have one limit per period per partner. So we should have:
For a given partner and period, we take the most specific config (partner-specific if exists, else global). And if there is no config for that period, then no limit.
So:
For each period (daily, monthly, lifetime) that we support:
config = CostLimitConfig.where(partner_id=partner_id, period=period).first()
if not config:
config = CostLimitConfig.where(partner_id=null, period=period).first()
if config:
// then we have a limit for this period.
Then we check only one config per period.
So we don't need a table of configs, we can have:
cost_limits:
id
partner_id (nullable)
period
limit_value
And then for a partner and period, we get:
cost_limit_config = CostLimitConfig.where(partner_id=partner_id, period=period).first() or CostLimitConfig.where(partner_id=null, period=period).first()
And then we use that limit.
But then we have to manage the global configs (partner_id null) and partner-specific configs.
Alternatively, we can have a partner_cost_limits table that stores the limit for each partner and period, and if a partner doesn't have a row, then we use the global default from a configuration table.
Let's create:
Table: cost_limit_defaults
period (primary key)
limit_value
Table: partner_cost_limits
id
partner_id
period
limit_value (if null, then use the default? but we can also have no row meaning use default)
Then, for a partner and period:
partner_limit = PartnerCostLimit.where(partner_id=partner_id, period=period).first()
if partner_limit:
limit_value = partner_limit.limit_value
else:
default = CostLimitDefault.where(period=period).first()
if default:
limit_value = default.limit_value
else:
// no limit for this period.
This way, we can set a global default for each period, and then override per partner.
But we also have to track the current cost for each partner and period. So we need the usage table (cost_limits) that we already have.
So we have:
cost_limit_defaults: (period, limit_value) // global default for each period
partner_cost_limits: (partner_id, period, limit_value) // overrides for partners
And then the current cost tracking table:
cost_limits:
id
partner_id
period
period_start
period_end
current_cost
And we check:
For each period (daily, monthly, lifetime) that we support:
// Get the limit for this partner and period.
limit_value = get_limit(partner_id, period)
if limit_value is not None:
// Find or create the current period's cost_limit row.
period_start, period_end = compute_period(period, now)
usage = CostLimit.where(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end).lock_for_update().first()
if not usage:
usage = CostLimit.create(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end, current_cost=0)
if usage.current_cost + request_cost > limit_value:
// fail
Then, if all pass, update all the usage rows for the periods that have a limit.
But note: the request_cost is the same for all periods. So we are adding the same request_cost to daily, monthly, and lifetime. That is correct.
Now, we have to define which periods we support. Let's say: daily, monthly, lifetime.
We also have to consider that the cost calculation might be different for different periods? No, the cost of the request is fixed.
Now, let's adjust the code for the cost part:
periods_to_check = ['daily', 'monthly', 'lifetime'] // or we can get from the cost_limit_defaults table?
for period in periods_to_check: limit_value = get_cost_limit(partner_id, period) if limit_value is None: continue
period_start, period_end = compute_period(period, now)
usage = CostLimit.where(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end).lock_for_update().first()
if not usage:
usage = CostLimit.create(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end, current_cost=0)
if usage.current_cost + request_cost > limit_value:
log_audit(...)
return error
// Then, if we get here, we update all the usage rows that we locked (we have to store them in a list) with the request_cost.
But note: we only locked the ones that have a limit. We must update exactly those.
So we can store the usage rows we locked in a list and then update them.
Now, the function get_cost_limit(partner_id, period):
partner_limit = PartnerCostLimit.where(partner_id=partner_id, period=period).first() if partner_limit: return partner_limit.limit_value else: default = CostLimitDefault.where(period=period).first() if default: return default.limit_value else: return None
We must also consider that the cost_limit_defaults table might not have a row for a period, meaning no default limit for that period.
Now, the overall code structure:
function handle_request(partner_id, data_in, data_out, endpoint): // Authenticate and check partner status partner = Partner.get(partner_id) if not partner or partner.status != 'active': log_audit(partner_id, 'api_request', data_in, data_out, 0, 'unauthorized' if not partner else 'revoked', ...) return error
// Quota checks
quota_configs = PartnerQuota.where(partner_id=partner_id).all()
// We'll store the usage rows we lock for quotas to update later.
quota_usages_to_update = []
// Sort quota_configs by (period, direction) to avoid deadlocks.
sorted_quota_configs = quota_configs.sort_by { |c| [c.period, c.direction] }
for config in sorted_quota_configs:
period = config.period
direction = config.direction
period_start, period_end = compute_period(period, now)
// Find or create the usage row for this period and direction.
usage = Quota.where(partner_id=partner_id, period=period, direction=direction, period_start=period_start, period_end=period_end).lock_for_update().first()
if not usage:
try:
usage = Quota.create(partner_id=partner_id, period=period, direction=direction, period_start=period_start, period_end=period_end, current_usage=0)
except UniqueViolation:
usage = Quota.where(partner_id=partner_id, period=period, direction=direction, period_start=period_start, period_end=period_end).lock_for_update().first()
// Check
add = (direction == 'in') ? data_in : data_out
if usage.current_usage + add > config.limit_value:
log_audit(partner_id, 'api_request', data_in, data_out, 0, 'quota_exceeded', {quota_id: config.id})
return error
quota_usages_to_update << {usage: usage, add: add}
// Cost limit checks
request_cost = calculate_request_cost(data_in, data_out, partner) // using partner.cost_per_unit or global?
cost_usages_to_update = []
periods = ['daily', 'monthly', 'lifetime']
for period in periods:
limit_value = get_cost_limit(partner_id, period)
if limit_value is None:
continue
period_start, period_end = compute_period(period, now)
usage = CostLimit.where(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end).lock_for_update().first()
if not usage:
try:
usage = CostLimit.create(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end, current_cost=0)
except UniqueViolation:
usage = CostLimit.where(partner_id=partner_id, period=period, period_start=period_start, period_end=period_end).lock_for_update().first()
if usage.current_cost + request_cost > limit_value:
log_audit(partner_id, 'api_request', data_in, data_out, request_cost, 'cost_exceeded', {period: period, limit: limit_value})
return error
cost_usages_to_update << usage
// Process the request
success = true
try:
// ... exchange data ...
except:
success = false
// Update quotas and cost if success
if success:
for item in quota_usages_to_update:
item.usage.current_usage += item.add
item.usage.save()
for usage in cost_usages_to_update:
usage.current_cost += request_cost
usage.save()
// Audit
log_audit(partner_id, 'api_request', data_in, data_out, request_cost, success ? 'success' : 'failure')
We must also consider that the request might be for data_in and data_out both, and we have quotas for both. We are checking each one independently.
The function calculate_request_cost:
We need to convert data_in and data_out to the unit of cost_per_unit (e.g., MB).
Let's assume we have a global cost_per_unit (if partner doesn't have one) and we store it in the partners table as cost_per_unit (in $/MB). But we might want to override per partner? We can have:
partner.cost_per_unit (if set, use it, else use global default)
We can have a table for global_cost_config with a field cost_per_unit.
Then:
def calculate_request_cost(data_in, data_out, partner):
global_config = GlobalCostConfig.first() // singleton
cost_per_unit = partner.cost_per_unit || global_config.cost_per_unit
total_mb = (data_in + data_out) / (1024.0 * 1024.0)
return total_mb * cost_per_unit
We also need to consider that the data_in and data_out might be 0? Then cost is 0.
Now, the audit log function:
def log_audit(partner_id, action, data_in, data_out, cost, status, details={}): AuditLog.create( actor_type: 'partner', actor_id: partner_id, action: action, partner_id: partner_id, data_in: data_in, data_out: data_out, cost: cost, status: status, details: details )
For admin actions, we can have a separate function that logs with actor_type='admin' and actor_id=admin_user_id.
We also need to consider that the request might not have both data_in and data_out? We are passing both to the function. We can set the one that is not applicable to 0.
Now, we have a basic design.
We also need to consider that the quotas and cost limits might be in different units? For example, the quota might be in bytes, but the cost_per_unit is per MB. That's okay because we convert for cost.
We must also consider that the quotas might be in records, not bytes. We assume the data_in and data_out are in the same unit as the quota.
We are now ready to implement.
However, note: the compute_period function:
For daily: period_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) period_end = period_start + timedelta(days=1)
For monthly: period_start = datetime.utcnow().replace(day=1, hour=0, minute=0, second=0, microsecond=0) if period_start.month == 12: period_end = datetime(period_start.year+1, 1, 1) else: period_end = datetime(period_start.year, period_start.month+1, 1)
For lifetime: period_start = datetime(1970,1,1) period_end = datetime(9999,12,31)
We must also consider that the compute_period function should return the period_start and period_end in UTC.
We are using UTC for everything.
Now, let's consider the admin actions:
Revoke a partner: set partner.status = 'revoked'
Reset a quota: we can reset the current_usage of a specific usage row? Or we can delete the usage row for the current period? If we delete, then next request will create a new row with 0. But we might want to keep the history.
We can have an admin action to reset the current_usage of a specific usage row to 0.
Adjust a quota limit: update the partner_quota.limit_value.
Adjust a cost limit: update the partner_cost_limits.limit_value or the default.
We can have an audit log for these admin actions.
We also need to consider that the system should be able to handle a large number of partners and requests.
We might want to cache the partner's status, quotas, and cost limits to reduce database load? But then we have to worry about cache invalidation.
Given the complexity, we might not cache and rely on the database with proper indexing.
Indexes:
partners: api_key (unique), status
partner_quotas: (partner_id, period, direction) unique
quotas: (partner_id, period, direction, period_start, period_end) unique, and also index on (partner_id, period, direction) for the query we do.
cost_limit_defaults: period (unique)
partner_cost_limits: (partner_id, period) unique
cost_limits: (partner_id, period, period_start, period_end) unique, and index on (partner_id, period) for the query.
Also, we are locking rows, so we need to make sure the queries use the indexes to lock quickly.
We are done with the design.
Let's summarize the tables:
Table: partners id name status (enum: 'active', 'revoked') api_key (unique) cost_per_unit (numeric, default from global config) // optional, if not set use global
Table: partner_quotas id partner_id (foreign key) period (enum: 'daily', 'monthly', 'lifetime') direction (enum: 'in', 'out') limit_value (numeric) unique (partner_id, period, direction)
Table: quotas id partner_id period direction period_start (date) period_end (date) current_usage (numeric) unique (partner_id, period, direction, period_start, period_end)
Table: cost_limit_defaults period (primary key) limit_value (numeric)
Table: partner_cost_limits id partner_id (foreign key) period (enum: 'daily', 'monthly', 'lifetime') limit_value (numeric) unique (partner_id, period)
Table: cost_limits id partner_id period period_start (date) period_end (date) current_cost (numeric) unique (partner_id, period, period_start, period_end)
Table: audit_logs id timestamp actor_type (enum: 'partner', 'admin') actor_id action partner_id data_in (numeric) data_out (numeric) cost (numeric) status details (jsonb)
We also need a table for global cost config? We have cost_limit_defaults for the limit, but we also need the cost_per_unit global default? We can have:
Table: global_cost_config id (singleton) cost_per_unit (numeric)
Then, in the partners table, cost_per_unit is nullable. If null, use global_cost_config.cost_per_unit.
Now, we have a complete design.
We must also consider that the request might be for a large amount of data and we might want to reject it before processing if the quota or cost is exceeded. That's why we check before processing.
We are ready to implement.
But note: the compute_period function for monthly: we have to be careful because the month might not have 31 days. We are using the first day of the next month as the period_end, which is correct.
Also, for daily, we are using UTC. If we want to use the partner's timezone, we need to store the partner's timezone and adjust. But for simplicity, we use UTC.
We might also want to have a way to change the partner's timezone? Then the period_start and period_end would be in that timezone? But then we have to store the period_start and period_end in UTC? Or we store the timezone and compute on the fly.
Given the complexity, we stick to UTC.
This design should meet the requirements.
We also need to consider that the audit log might grow large. We can partition by month or year.
We also need to consider that the quotas and cost_limits tables will have one row per partner per period per direction (and per period for cost). For daily, that's one row per day per partner per direction. That could be a lot of rows. We can archive old rows? Or we can keep them for history.
We can have a job that deletes or archives rows older than a certain period (e.g., 2 years) for daily quotas? But we might want to keep for auditing.
We can move old rows to a separate table (archive) and keep only the current period and maybe the last few periods in the main table.
But for simplicity, we keep all rows.
We are done.