openapi: 3.0.3
info:
title: Leased Resource API
description: |
A RESTful API for managing leased access to resources with fencing, TTL-based expiration, and automatic cleanup.
## Key Concepts
- **Lease**: Exclusive access to a resource for a TTL duration.
- **Fencing**: Uses a unique, opaque `fenceToken` (UUIDv4) per lease. All mutating operations require this token in the `X-Fence-Token` header.
- Protects against stale clients: operations fail (409 Conflict) if token mismatches current active lease or lease is expired.
- **TTL**: Server-enforced expiration. Clients must renew before expiry.
- **Cleanup**: Server runs a background goroutine/cron (every 30s) scanning active leases:
- If `expiresAt < now`, atomically clear the lease (set to null).
- Uses database transactions/ACID guarantees for atomicity (e.g., PostgreSQL with row locks or etcd-like compare-and-swap).
- **Storage**: Assumes a durable store (e.g., PostgreSQL table `resource_leases` with columns: `resource_id`, `lease_id`, `fence_token`, `expires_at`, `created_at`).
- **Idempotency**: Lease acquire is idempotent if client retries with same TTL (but generates new tokens).
- **Error Handling**: Standard HTTP codes + JSON error bodies.
- **Auth**: Assumes bearer token auth (omitted for brevity).
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
/resources/{resourceId}/lease:
post:
summary: Acquire a lease on the resource
description: Atomically creates a new lease if none active or expired. Returns `leaseId` and `fenceToken` for fencing.
parameters:
- name: resourceId
in: path
required: true
schema:
type: string
pattern: '^[a-zA-Z0-9_-]{1,255}$'
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [ttlSeconds]
properties:
ttlSeconds:
type: integer
minimum: 10
maximum: 3600 # 1 hour max
metadata:
type: object
description: Optional client metadata (e.g., {"clientId": "foo"})
responses:
'201':
description: Lease acquired
content:
application/json:
schema:
type: object
required: [leaseId, fenceToken, expiresAt]
properties:
leaseId:
type: string
format: uuid
description: Unique lease identifier
fenceToken:
type: string
description: Opaque token for fencing (pass in X-Fence-Token header)
expiresAt:
type: string
format: date-time
description: UTC expiration timestamp
metadata:
type: object
description: Echoed client metadata
'409':
description: Lease already active (non-expired)
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'400':
$ref: '#/components/responses/BadRequest'
get:
summary: Get current lease status
parameters:
- name: resourceId
in: path
required: true
schema:
type: string
responses:
'200':
description: Lease status (active or expired/cleared)
content:
application/json:
schema:
type: object
properties:
leaseId:
type: string
format: uuid
nullable: true
fenceToken:
type: string
nullable: true
expiresAt:
type: string
format: date-time
nullable: true
isActive:
type: boolean
description: true if not expired (post-cleanup)
'404':
description: Resource not found (no lease history)
/resources/{resourceId}/lease/{leaseId}:
put:
summary: Renew lease TTL
description: Extends TTL if `leaseId` matches active lease and not expired. Requires valid `X-Fence-Token`.
parameters:
- name: resourceId
in: path
required: true
schema:
type: string
- name: leaseId
in: path
required: true
schema:
type: string
format: uuid
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [ttlSeconds]
properties:
ttlSeconds:
type: integer
minimum: 10
maximum: 3600
headers:
X-Fence-Token:
required: true
schema:
type: string
description: Must match current active fenceToken
responses:
'200':
description: Lease renewed
content:
application/json:
schema:
type: object
required: [expiresAt]
properties:
expiresAt:
type: string
format: date-time
'409':
description: Invalid/expired lease or fence token mismatch
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: Lease or resource not found
delete:
summary: Release lease voluntarily
description: Releases if `leaseId` matches and `X-Fence-Token` valid. Idempotent.
parameters:
- name: resourceId
in: path
required: true
schema:
type: string
- name: leaseId
in: path
required: true
schema:
type: string
format: uuid
headers:
X-Fence-Token:
required: true
schema:
type: string
responses:
'204':
description: Lease released
'409':
description: Invalid/expired lease or fence token mismatch
'404':
description: Lease or resource not found
/resources/{resourceId}/fenced-operation:
post:
summary: Perform a fenced operation on the resource
description: |
Example mutating operation (e.g., update state). Fails if lease invalid/expired.
Server atomically:
1. Validate fenceToken and !expired.
2. Apply operation.
3. Optionally auto-renew TTL by N seconds (configurable).
Customizable via operation type (e.g., "update", "delete").
parameters:
- name: resourceId
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [operation, payload]
properties:
operation:
type: string
enum: [update, snapshot, custom]
payload:
type: object
description: Operation-specific data (e.g., {"newState": "active"})
headers:
X-Fence-Token:
required: true
schema:
type: string
responses:
'200':
description: Operation succeeded
content:
application/json:
schema:
type: object
properties:
result:
type: object
newExpiresAt:
type: string
format: date-time
description: Updated expiry if auto-renewed
'409':
description: Stale fence token or expired lease
'400':
$ref: '#/components/responses/BadRequest'
/admin/cleanup:
post:
summary: Manual cleanup trigger (admin only)
description: Force immediate scan and expire all leases where expiresAt < now.
responses:
'200':
description: Cleanup complete
content:
application/json:
schema:
type: object
properties:
expiredCount:
type: integer
timestamp:
type: string
format: date-time
security:
- admin: []
components:
schemas:
Error:
type: object
required: [code, message]
properties:
code:
type: string
enum: [LEASE_ACTIVE, FENCE_MISMATCH, EXPIRED, INVALID_TTL]
message:
type: string
responses:
BadRequest:
description: Invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
securitySchemes:
bearerAuth:
type: http
scheme: bearer
Implementation Notes
- Backend Logic (pseudocode):
type Lease struct {
ResourceID string `db:"resource_id"`
LeaseID uuid.UUID `db:"lease_id"`
FenceToken string `db:"fence_token"` // UUIDv4, indexed
ExpiresAt time.Time `db:"expires_at"`
Metadata json.RawMessage
}
// Acquire (transactional)
func acquire(ctx, resourceID string, ttlSec int) (*Lease, error) {
now := time.Now()
row := db.QueryRowx(`
SELECT * FROM resource_leases
WHERE resource_id = ? AND expires_at > ? FOR UPDATE`,
resourceID, now)
var existing Lease
if err := row.StructScan(&existing); err == nil && !existing.ExpiresAt.IsZero() {
return nil, ErrLeaseActive // 409
}
leaseID := uuid.New()
fenceToken := uuid.NewString()
expiresAt := now.Add(time.Duration(ttlSec) * time.Second)
_, err := db.Exec(`
INSERT INTO resource_leases (resource_id, lease_id, fence_token, expires_at)
VALUES (?, ?, ?, ?) ON CONFLICT (resource_id) DO UPDATE SET ...`,
resourceID, leaseID, fenceToken, expiresAt)
return &Lease{...}, err
}
// ValidateFencedOp
func validateFenced(ctx, resourceID, fenceToken string) (*Lease, error) {
lease, err := getActiveLease(resourceID) // SELECT ... WHERE expires_at > NOW()
if err != nil || lease.FenceToken != fenceToken {
return nil, ErrFenceMismatch // 409
}
return lease, nil
}
// Background Cleanup (every 30s)
func cleanup() {
_, _ = db.Exec(`UPDATE resource_leases SET lease_id=NULL, fence_token=NULL, expires_at=NULL
WHERE expires_at < NOW()`)
}
- Client Usage Example (pseudocode):
// Acquire
const lease = await fetch(`/v1/resources/foo/lease`, { method: 'POST', body: {ttlSeconds: 60} });
const {fenceToken} = await lease.json();
// Renew (loop every 50s)
setInterval(async () => {
await fetch(`/v1/resources/foo/lease/${leaseId}`, {
method: 'PUT',
headers: {'X-Fence-Token': fenceToken},
body: {ttlSeconds: 60}
});
}, 50000);
// Fenced operation
await fetch(`/v1/resources/foo/fenced-operation`, {
method: 'POST',
headers: {'X-Fence-Token': fenceToken},
body: {operation: 'update', payload: {state: 'processed'}}
});
- Edge Cases Handled:
- Network partitions: TTL fencing prevents stale writes.
- Clock skew: Use server time only.
- High contention: DB locks ensure atomicity.
- Scale: Shard by
resourceId hash if needed.
- Observability: Log all 409s, metrics for lease duration/utilization.
This design is production-ready, secure against race conditions, and aligns with patterns in etcd, Consul, and Kubernetes leases.