API Design:
We'll design a RESTful API (or gRPC) for the lease service.
Endpoints:
a. POST /leases
Request: { resource_id, owner_id, ttl (in seconds) }
Response: { lease_id, expiration_time, version (for fencing) }
- This creates a new lease for the given resource. If there's an existing lease for the same resource that is still active, we might:
Option 1: Fail the request (because the resource is already leased).
Option 2: Force revoke the old lease and create a new one (if we want to allow preemption).
Let's assume we allow preemption: if there's an existing active lease, we revoke it (and do fencing for the old owner) and then create the new lease.
Steps for creating a lease:
1. Check if there's an active lease for the resource.
2. If yes, revoke the old lease (mark as REVOKED) and record the revocation time.
3. Create a new lease with a new lease_id (or version). The version should be greater than the old one.
However, note: in a distributed system, we must do this atomically to avoid race conditions.
We can use a database transaction or a distributed lock. Alternatively, if we use a consensus algorithm, we can log the operation and apply it atomically.
b. PUT /leases/{lease_id}/renew
Request: { ttl }
Response: { expiration_time, version }
- Renews the lease for the given lease_id. The lease_id must be the current active lease for the resource.
- We update the expiration_time to current time + ttl.
- We might also increment a version number? Actually, we don't need to increment version on renew because the lease_id remains the same? But for fencing, we want to ensure that the old lease cannot be used after renewal? Actually, renewal doesn't change the lease_id, so if an attacker holds the old lease_id, they can still use it until it expires? That's a problem.
Solution: On renew, we should change the lease_id (or version) to prevent the old lease from being used. But then the client must update its local copy of the lease_id. Alternatively, we can have a separate field for the version that increments on every change (create, renew, revoke). Then, when accessing the resource, we check that the version in the lease matches the current version for that resource.
Let's adjust the data model:
Lease: { lease_id (unique), resource_id, owner_id, version (monotonically increasing per resource), expiration_time, status }
Then, when we create or renew, we increment the version for the resource. The lease_id is a unique identifier for the lease, but the version is what we use for fencing (because we compare the version in the request with the current version of the resource).
However, note: if we have multiple resources, we want the version to be per resource. So we can have a separate version counter per resource? Or we can have a global version? Actually, we want the version to be increasing for the same resource. So we can store the current version for each resource in the resource table (or in the lease as the version of the lease, but when we renew we create a new lease with a higher version?).
Alternatively, we can have:
Resource: { resource_id, current_version, current_lease_id }
Then, when we create a lease:
- We create a lease with a new lease_id and a version = current_version+1.
- We update the resource to point to this lease and set current_version = version.
Then, when renewing:
- We create a new lease (with a new lease_id) and a version = current_version+1, and update the resource.
But then we have multiple leases for the same resource (old ones) that are expired. We can keep them for history? Or we can delete the old lease? We might want to keep the old leases for auditing.
Alternatively, we can update the existing lease (same lease_id) and increment the version? Then the lease_id remains the same but the version changes. That way, the client only needs to remember the lease_id and the version? Actually, the client must present both the lease_id and the version? Or just the lease_id? We want to ensure that the lease_id is valid and the version is current.
Let's think: when we create a lease, we return the lease_id and the version. The client must present both to access the resource? But the resource guard (which might be a separate service) must check that the lease_id exists and is active and that the version matches the current version of the resource.
Alternatively, we can have the resource guard check the lease by lease_id and then check that the lease's version matches the resource's current version. Then we don't need to send the version from the client, just the lease_id.
So:
Step for creating a lease:
1. Read the current lease for the resource (if any) and its version.
2. Create a new lease with:
lease_id = new UUID
version = old_version + 1 (or 1 if none)
resource_id, owner_id, expiration_time, status=ACTIVE
3. Update the resource to point to the new lease_id and set the current_version to the new version.
Then, when accessing a resource, the client sends the lease_id. The guard:
- Looks up the lease by lease_id.
- Checks that the lease is ACTIVE and that the lease's version matches the resource's current_version.
If the lease exists but the version doesn't match, then it's an old lease (maybe because the lease was renewed or revoked) and access is denied.
How about renewal? We can do the same: create a new lease (with new lease_id and version = current_version+1) and update the resource.
But then we have many leases for the same resource. We might want to clean up old leases.
Alternatively, we can update the existing lease (same lease_id) and increment the version? Then we don't create a new lease. But then the lease_id remains the same, and the client doesn't need to update the lease_id? But then if an attacker intercepts the old lease_id, they can still use it because the lease_id is the same? But the version in the lease has changed. So when the guard checks, it will see that the lease's version is higher than the one the client has? Actually, the client doesn't send the version, so the guard will just check the lease's version against the resource's current version. If we update the lease's version, then the resource's current version is updated too, so the old lease (with the same lease_id but old version) is no longer valid.
But wait: if we update the existing lease, then the lease_id remains the same and the version is incremented. Then the client must re-fetch the lease to get the new version? But the client doesn't send the version. So the guard only uses the lease_id to look up the lease, and then compares the lease's version with the resource's current version. So if we update the lease's version and the resource's current version, then the old lease (with the same lease_id) now has an old version and will be rejected.
However, note: if we update the existing lease, then we are changing the lease's version. But the lease_id is the same. So if the client presents the lease_id, we look up the lease and see the new version, and the resource's current version is the same, so it matches.
But what if we want to revoke a lease? We set the lease's status to REVOKED and update the resource's current version? Actually, if we revoke, we don't want the lease to be valid anymore. So we set status=REVOKED and then update the resource's current version to a new value (so that any old lease, even if it's the same lease_id, is invalid because the version doesn't match). But note: if we revoke, we might want to assign a new lease to another owner. Then we create a new lease (with new lease_id and new version) and update the resource.
So, in summary:
- Each resource has a current_lease_id and a current_version.
- Each lease has a version (which must match the resource's current_version when the lease is active).
- When we create a lease (or renew), we create a new lease (with a new lease_id) and a new version (current_version+1) and update the resource.
- When we revoke, we set the lease's status to REVOKED and then update the resource's current_version to a new value (so that the old lease becomes invalid). But note: if we revoke without assigning a new lease, we still update the resource's current_version? We must, because otherwise the old lease (with the same lease_id) would still have the same version and would be considered valid? But we set the lease status to REVOKED, so we check status too.
Actually, we can do:
Guard check:
1. Look up the lease by lease_id.
2. Check that the lease.status is ACTIVE.
3. Check that the lease.version == resource.current_version.
So if we revoke a lease, we set status=REVOKED and then update the resource's current_version to a new value (even if we don't assign a new lease). Then the old lease will fail step 3 because the version doesn't match.
But note: if we revoke and then assign a new lease, we update the resource's current_version to the new lease's version. Then the old lease fails step 3.
So the process for creating a lease (with preemption):
BEGIN TRANSACTION
Read the current resource state (current_lease_id, current_version).
If there is a current_lease_id, read that lease and set its status to REVOKED.
Create a new lease with:
lease_id = new UUID
version = current_version + 1
resource_id, owner_id, expiration_time = now + ttl, status = ACTIVE
Update the resource: set current_lease_id = new lease_id, current_version = new version.
COMMIT
Renewal (for a given lease_id):
We want to renew the lease that is currently active (so the lease_id must be the current_lease_id of the resource). But note: we are going to create a new lease? Or update the existing one?
If we update the existing lease (same lease_id) and increment the version, then:
BEGIN TRANSACTION
Read the resource to get current_lease_id and current_version.
If current_lease_id != given lease_id, fail (because the lease is not current).
Read the lease by lease_id (the current one) and update:
expiration_time = now + ttl
version = current_version + 1 [but wait, we are updating the same lease, so the lease's version becomes current_version+1]
Update the resource: current_version = current_version + 1 (and current_lease_id remains the same).
COMMIT
But then we have the same lease_id with a new version. That's okay because the resource's current_version is updated.
Alternatively, we can create a new lease (with new lease_id) and update the resource to point to the new lease. This is what we did for create. But then the client must update its lease_id? That might be disruptive.
Let's stick to updating the existing lease for renewal. Then the client doesn't need to change the lease_id, but the version changes. However, the client doesn't use the version, so it's okay.
But note: if we update the existing lease, then the lease_id remains the same. Then if an attacker has the lease_id, they can keep using it? But the version changes, so the guard will check the lease's version against the resource's current_version. Since we update both, the lease is still valid. But what if we want to revoke the lease? We set the lease's status to REVOKED and update the resource's current_version. Then the lease_id is the same but the version doesn't match and the status is REVOKED, so it fails.
However, if we update the existing lease for renewal, then we are changing the lease's version and expiration. But the lease_id is the same. So if the client doesn't update its lease_id (it doesn't need to), then it's okay.
But what if we want to force revoke a lease? We set the lease's status to REVOKED and update the resource's current_version. Then the lease_id is still the same, but the version is old and status is REVOKED, so it fails.
So both approaches work. However, if we create a new lease on renewal, then we have multiple leases for the same resource (old and new). We might want to clean up old leases.
Let's choose:
For simplicity, we will create a new lease on every operation (create and renew) and update the resource to point to the new lease. This way, we have a clear history and we can easily clean up old leases by deleting leases that are not the current one and are expired.
But then the client must update the lease_id on every renewal? That might be a burden. Alternatively, we can return the same lease_id and just update the expiration and version? But then we don't have a new lease_id.
Actually, we can have two concepts:
- lease_id: unique identifier for the lease (never changes for a given lease).
- version: updated on every change (create, renew, revoke) for the resource.
Then, when we renew, we update the same lease (same lease_id) and increment the version. Then the client doesn't need to change the lease_id.
But then how do we clean up old leases? We can delete leases that are not the current one and are expired? But if we update the same lease, then there is only one lease per resource (until we revoke and create a new one). Actually, when we revoke, we set the lease to REVOKED and then create a new lease (with new lease_id). So we have two leases for the same resource: the old one (REVOKED) and the new one (ACTIVE). We can delete the old one after some time.
So:
Operation create (with preemption):
- If there's an active lease, revoke it (set status=REVOKED) and update the resource's current_version (so that the old lease becomes invalid) but we don't delete it immediately.
- Then create a new lease (new lease_id, version = old_version+1) and set the resource to point to it.
Operation renew (for a given lease_id):
- Check that the lease_id is the current_lease_id of the resource and that the lease is ACTIVE.
- Update the lease: set expiration_time = now + ttl, version = current_version + 1.
- Update the resource: current_version = current_version + 1.
Operation revoke (for a given lease_id):
- Check that the lease_id is the current_lease_id and that the lease is ACTIVE.
- Set the lease status to REVOKED.
- Update the resource: current_version = current_version + 1 (and we might set current_lease_id to null? or leave it as the revoked lease? Actually, we should set current_lease_id to null because there's no active lease. But then if we want to assign a new lease, we create a new lease and set current_lease_id to that.
So after revoke, the resource has no active lease (current_lease_id is null) and the old lease is REVOKED.
Then, when we create a new lease (without preemption, because there's no active lease) we create a new lease and set current_lease_id to it and current_version = 1 (or the old version+1? We can just set to 1 because there's no old version? Actually, we can keep incrementing the version even when there's no lease? Or reset? Let's keep incrementing: we can store the last version used for the resource and increment it every time we change the lease (even if we revoke without assigning a new lease). But then when we create a new lease, we set the version to last_version+1.
Alternatively, we can have the version be per lease? But we want the resource to have a current_version that must match the lease's version. So the version is tied to the resource's state.
So we can store:
Resource:
resource_id (PK)
current_lease_id (nullable, FK to lease.lease_id)
current_version (integer)
Lease:
lease_id (PK)
resource_id (FK to resource)
owner_id
version (integer, must match resource.current_version when active)
expiration_time
status (ACTIVE, EXPIRED, REVOKED)
Then:
Create lease (with preemption):
BEGIN TRANSACTION
resource = SELECT * FROM resources WHERE resource_id = ? FOR UPDATE
if resource.current_lease_id is not null:
old_lease = SELECT * FROM leases WHERE lease_id = resource.current_lease_id FOR UPDATE
UPDATE leases SET status = 'REVOKED' WHERE lease_id = old_lease.lease_id
new_version = resource.current_version + 1
new_lease_id = generate_uuid()
INSERT INTO leases (lease_id, resource_id, owner_id, version, expiration_time, status)
VALUES (new_lease_id, resource_id, owner_id, new_version, now() + ttl, 'ACTIVE')
UPDATE resources SET current_lease_id = new_lease_id, current_version = new_version
WHERE resource_id = resource_id
COMMIT
Renew lease (by lease_id):
BEGIN TRANSACTION
lease = SELECT * FROM leases WHERE lease_id = ? FOR UPDATE
resource = SELECT * FROM resources WHERE resource_id = lease.resource_id FOR UPDATE
if resource.current_lease_id != lease.lease_id or lease.status != 'ACTIVE':
abort
new_version = resource.current_version + 1
UPDATE leases SET expiration_time = now() + ttl, version = new_version WHERE lease_id = lease.lease_id
UPDATE resources SET current_version = new_version WHERE resource_id = lease.resource_id
COMMIT
Revoke lease (by lease_id):
BEGIN TRANSACTION
lease = SELECT * FROM leases WHERE lease_id = ? FOR UPDATE
resource = SELECT * FROM resources WHERE resource_id = lease.resource_id FOR UPDATE
if resource.current_lease_id != lease.lease_id or lease.status != 'ACTIVE':
abort
UPDATE leases SET status = 'REVOKED' WHERE lease_id = lease.lease_id
new_version = resource.current_version + 1
UPDATE resources SET current_lease_id = NULL, current_version = new_version WHERE resource_id = lease.resource_id
COMMIT
Then, to check if a lease is valid for a resource (fencing):
function is_valid(resource_id, lease_id):
resource = SELECT current_lease_id, current_version FROM resources WHERE resource_id = ?
if resource.current_lease_id is null:
return false
lease = SELECT version, status FROM leases WHERE lease_id = resource.current_lease_id
if lease.status != 'ACTIVE':
return false
if lease.version != resource.current_version:
return false
if lease.expiration_time < now():
return false // but we should have a background job that sets status to EXPIRED? Or we check expiration here?
return true
We can also have a background job that sets lease.status to EXPIRED if expiration_time < now and status is ACTIVE. But note: the above check already checks expiration. However, we might want to mark it as EXPIRED for cleanup.
Alternatively, we can have a cron job that:
UPDATE leases SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND expiration_time < now();
Then, in the above check, we only check status != 'ACTIVE' (which includes EXPIRED and REVOKED).
But note: what if the lease is ACTIVE but expired? We might have a race condition: the lease expires between the time we check and the time we use the resource? But we check expiration in the is_valid function? Actually, we don't want to rely on the client's clock. We can have the guard check the expiration against the server's time.
So we can do:
In is_valid, we check:
- resource.current_lease_id is not null
- lease.status is ACTIVE
- lease.version == resource.current_version
- lease.expiration_time > now()
Then we don't need to update the status to EXPIRED? But we want to clean up expired leases. We can have a background job that sets status to EXPIRED for leases that are ACTIVE and expired, and then we can delete them (or mark for deletion) after some time.
Alternatively, we can have the background job delete the leases that are EXPIRED or REVOKED and are older than a certain threshold.
But note: if we set status to EXPIRED, then the is_valid will fail because status != ACTIVE.
So:
Background job (runs every minute):
UPDATE leases SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND expiration_time < now();
Then, we can have another job that deletes leases that are EXPIRED or REVOKED and are older than, say, 1 day.
However, we might want to keep the history of leases for a while. So we can move them to an archive table.
But for simplicity, we can just delete them.
Also, we need to clean up resources that have no active lease? Actually, the resource exists independently. We don't delete the resource from the resource table when the lease expires. The resource table is for tracking the current lease. We might want to delete the resource if it's no longer used? But that's a separate problem.
So, the cleanup:
- Periodically mark expired leases as EXPIRED.
- Periodically delete leases that are EXPIRED or REVOKED and are older than a threshold (e.g., 1 day).
But note: we might have a lease that is ACTIVE and expired? The background job will mark it as EXPIRED. Then we can delete it after some time.
Alternatively, we can delete the lease immediately when it expires? But we might want to keep it for debugging. So we mark as EXPIRED and then delete later.
Also, note that when we revoke, we set the lease to REVOKED. We might want to delete revoked leases after some time.
So:
Job 1 (runs every minute):
UPDATE leases SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND expiration_time < now();
Job 2 (runs once a day):
DELETE FROM leases WHERE status IN ('EXPIRED', 'REVOKED') AND updated_at < now() - interval '1 day';
We assume we have an updated_at column that is set on every update.
But note: when we revoke, we set status to REVOKED and update the lease. So updated_at is set. Then after 1 day, we delete it.
However, what about the resource table? We don't delete the resource row. We might want to delete the resource row if it's no longer leased? But the resource might be a physical resource (like a VM) that we want to deallocate when the lease expires. That's a separate concern.
Our lease service only tracks leases. The actual resource allocation and deallocation is done by another service that listens to lease events (or polls the lease service). For example, when a lease is revoked (or expired), the resource manager can deallocate the resource.
So, we can have:
- When a lease is revoked (by the revoke API) or expired (by the background job), we publish an event (or update a status that the resource manager watches) so that the resource can be cleaned up.
But note: the resource manager might already have deallocated the resource when the lease expired? Actually, the resource manager should check the lease status when trying to use the resource? Or we can have the lease service notify the resource manager.
Let's assume we have a resource manager that:
- When a lease is created (and the resource is allocated), it stores the lease_id and the resource.
- It periodically checks the lease service to see if the lease is still active (using the is_valid function). If not, it deallocates the resource.
Alternatively, we can have the lease service call the resource manager's API when a lease is revoked/expired.
But that introduces coupling.
We can design:
- The lease service does not manage the resources. It only tracks leases.
- The resource manager is responsible for checking the lease validity before using the resource and for deallocating the resource when the lease is no longer valid.
Then, the resource manager must:
- When it wants to use a resource, it checks the lease service (or has a cached copy) to see if the lease is valid.
- If not, it deallocates the resource and releases it.
But then the resource manager must be able to handle the case where the lease is revoked by someone else? Yes, because when it checks, it will see that the lease is not valid (because the version changed or status changed).
So, the resource manager should:
- Before using the resource, check the lease (by lease_id) and see if it's valid (using the is_valid function).
- If invalid, deallocate the resource and stop using it.
And the resource manager might also have a background job that periodically checks all resources it manages and verifies the lease.
Now, the API for the lease service:
We have:
POST /leases
PUT /leases/{lease_id}/renew
PUT /leases/{lease_id}/revoke
And we need an endpoint to check the lease? Actually, the resource manager will call the lease service to check the lease. But we don't want to expose the entire lease? We can have:
GET /leases/{lease_id}
But that returns the lease. Then the resource manager must also get the resource's current_version? Alternatively, we can have an endpoint that checks validity:
GET /resources/{resource_id}/lease-valid?lease_id={lease_id}
But that might be inefficient because the resource manager already knows the lease_id and the resource_id? Actually, the resource manager knows the resource_id and the lease_id (from when it acquired the lease). Then it can call:
POST /leases/check
Request: { resource_id, lease_id }
Response: { valid: boolean }
But then we are doing two lookups: one for the resource and one for the lease. We can do:
SELECT resource.current_lease_id, resource.current_version, lease.version, lease.status, lease.expiration_time
FROM resources
JOIN leases ON resources.current_lease_id = leases.lease_id
WHERE resources.resource_id = ? AND leases.lease_id = ?
Then check:
- resource.current_lease_id == lease_id (from the join, it should be)
- lease.status == ACTIVE
- lease.version == resource.current_version
- lease.expiration_time > now()
But note: if the lease is not the current lease, then the join won't return a row? Actually, we are joining on current_lease_id = lease_id. So if the lease_id is not the current lease, then no row. Then we return invalid.
Alternatively, we can do:
SELECT r.current_lease_id, r.current_version, l.version as lease_version, l.status, l.expiration_time
FROM resources r
LEFT JOIN leases l ON r.current_lease_id = l.lease_id
WHERE r.resource_id = ?
Then, if the current_lease_id is null, then no lease. Otherwise, we have the lease. Then we check:
if current_lease_id is null -> invalid
if l.status is null -> invalid? Actually, if the current_lease_id is set but the lease doesn't exist (or was deleted) then l.status is null -> invalid.
Then check l.status == 'ACTIVE', l.version == r.current_version, and l.expiration_time > now().
But we are given the lease_id in the request. We want to check that the given lease_id is the current_lease_id and that it is valid.
So:
SELECT r.current_lease_id, r.current_version, l.version as lease_version, l.status, l.expiration_time
FROM resources r
LEFT JOIN leases l ON r.current_lease_id = l.lease_id
WHERE r.resource_id = ?
Then, if r.current_lease_id != given lease_id, then invalid.
Then, if l.status != 'ACTIVE' -> invalid.
Then, if l.version != r.current_version -> invalid.
Then, if l.expiration_time <= now() -> invalid.
But note: we have a background job that sets status to EXPIRED when expiration_time < now, so we might not need to check expiration? But we do because the background job might not have run yet.
So we check both: status must be ACTIVE and expiration_time > now.
Alternatively, we can skip checking expiration if we trust the background job? But there's a race condition. So we check.
Now, the endpoints:
We'll design:
POST /leases
Request body:
{
"resource_id": "string",
"owner_id": "string",
"ttl": 3600 // in seconds
}
Response:
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": 1,
"expiration_time": "2024-01-01T00:00:00Z",
"status": "ACTIVE"
}
PUT /leases/{lease_id}/renew
Request body:
{
"ttl": 3600
}
Response:
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": 2, // incremented
"expiration_time": "2024-01-01T01:00:00Z",
"status": "ACTIVE"
}
PUT /leases/{lease_id}/revoke
Response:
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": 3, // incremented
"expiration_time": "2024-01-01T00:00:00Z", // unchanged
"status": "REVOKED"
}
And then the check endpoint:
GET /resources/{resource_id}/lease-check?lease_id={lease_id}
Response:
{
"valid": true,
"current_lease_id": "uuid",
"current_version": 2,
"lease_version": 2,
"status": "ACTIVE",
"expiration_time": "2024-01-01T01:00:00Z"
}
But note: we don't want to expose too much. Maybe just:
{
"valid": true
}
But for debugging, we might want to expose more.
Alternatively, we can have:
GET /leases/{lease_id}
Returns the lease.
Then the resource manager can:
lease = GET /leases/{lease_id}
resource = GET /resources/{resource_id} (to get current_lease_id and current_version)
Then check:
if resource.current_lease_id != lease.lease_id -> invalid
if lease.status != 'ACTIVE' -> invalid
if lease.version != resource.current_version -> invalid
if lease.expiration_time <= now() -> invalid
But that's two calls. We can combine into one.
Let's have:
GET /resources/{resource_id}/lease
Returns:
{
"current_lease_id": "uuid",
"current_version": 2,
"lease": {
"lease_id": "uuid",
"owner_id": "string",
"version": 2,
"expiration_time": "...",
"status": "ACTIVE"
}
}
Then the resource manager can check the lease_id it has against current_lease_id and then check the lease's version and status.
But note: the lease in the response is the current lease (which is the one pointed by current_lease_id). So if the given lease_id is not the current_lease_id, then it's invalid.
So:
if given_lease_id != response.current_lease_id -> invalid
else, check response.lease.status and version.
However, if the current_lease_id is null, then response.lease is null? We can design:
{
"current_lease_id": null,
"current_version": null,
"lease": null
}
Then if current_lease_id is null, invalid.
But we are given a lease_id, so we can just check:
if response.current_lease_id == given_lease_id and response.lease is not null and response.lease.status == 'ACTIVE' and response.lease.version == response.current_version and response.lease.expiration_time > now() -> valid.
But wait: the lease's version should equal the current_version? Yes, by our design.
So we can just check:
valid = (response.current_lease_id == given_lease_id) &&
(response.lease != null) &&
(response.lease.status == 'ACTIVE') &&
(response.lease.expiration_time > now())
Because the version in the lease must equal the current_version (by our update logic). But what if there's a bug? We can also check:
if response.lease.version != response.current_version -> invalid? But that should never happen.
So we can skip that check.
Alternatively, we can have the check endpoint do:
GET /resources/{resource_id}/lease-check?lease_id={lease_id}
Response:
{
"valid": true
}
And the server does the check as above.
But then we are doing the same check in two ways.
Let's have one endpoint that returns the current lease for a resource:
GET /resources/{resource_id}/lease
And then the client (resource manager) does the check locally.
Or we can have:
GET /resources/{resource_id}/lease?lease_id={lease_id}
And return:
{
"valid": true,
"lease": { ... } // only if valid? or always return the current lease?
}
But if the lease_id is not the current one, then valid=false, and we don't return the lease? Or we return the current lease? Actually, we want to know the current lease? Maybe for debugging.
Alternatively, we can have:
GET /resources/{resource_id}/lease
Returns the current lease (if any). Then the client compares the lease_id.
But then the client must also check the expiration? Yes.
So:
current_lease = GET /resources/{resource_id}/lease
if current_lease is null -> invalid
if current_lease.lease_id != given_lease_id -> invalid
if current_lease.status != 'ACTIVE' -> invalid
if current_lease.expiration_time <= now() -> invalid
And we don't need to check version because the lease we get is the current one, so its version must be the current_version? But we don't have the current_version in the lease response? We can include it in the lease response? Or we can have:
The lease object includes version, and the resource has current_version? But we are only returning the lease.
Actually, the lease has a version, and the resource has a current_version. They must match. But if we return the lease, and the lease's version is the same as the resource's current_version (which it is, by our design), then we don't need to return the resource's current_version separately.
But wait: the lease's version is set when we create/renew/revoke. And the resource's current_version is set to the same value. So they are the same. So we only need to check the lease's version? Actually, we don't need to check the version at all if we trust that the lease we get is the current one? But the client is comparing the lease_id. So if the lease_id is the current one, then the lease's version is the current_version. So we don't need to compare versions.
Then the check reduces to:
current_lease = GET /resources/{resource_id}/lease
if current_lease is null -> invalid
if current_lease.lease_id != given_lease_id -> invalid
if current_lease.status != 'ACTIVE' -> invalid
if current_lease.expiration_time <= now() -> invalid
But what if the lease is ACTIVE and not expired, but the version is not the current_version? That cannot happen because we update the lease's version and the resource's current_version together. So if the lease_id is the current_lease_id, then the lease's version must be the current_version.
So we can skip the version check.
However, note: we have a background job that sets the status to EXPIRED when the lease expires. So we don't need to check expiration? We do, because the background job might not have run yet. So we check expiration.
So the resource manager can do:
lease = get_current_lease(resource_id) // via API
if lease and lease.lease_id == my_lease_id and lease.status == 'ACTIVE' and lease.expiration_time > now():
valid
else:
invalid
But what if the lease is ACTIVE and not expired, but the version changed? That would mean the lease_id is not the current_lease_id? Because if the version changed, we updated the lease (same lease_id) and the resource's current_version. So the lease_id remains the same. So the version change doesn't affect the lease_id.
Wait: in our design, when we renew, we update the same lease (same lease_id) and increment the version. So the lease_id remains the same. Then the client doesn't need to update the lease_id. But then the client's lease_id is still valid because the lease_id is the same and the version is updated.
But what if we create a new lease (with new lease_id) on renewal? Then the client must update the lease_id. We decided to update the same lease for renewal? Let's stick to updating the same lease for renewal.
Then, for renewal, we don't create a new lease_id. So the client's lease_id remains the same.
But then, if we revoke and create a new lease, the lease_id changes.
So the client must handle:
- On create: gets a new lease_id.
- On renew: the same lease_id, but the version changes (but the client doesn't care about version).
- On revoke (by someone else): the lease_id becomes invalid because the resource's current_lease_id changes to a new one (or null). So the client must check the current lease_id and see that it's not the same.
So the client (resource manager) must periodically check the current lease_id for the resource and compare with its own lease_id.
Now, let's design the API with updating the same lease for renewal:
Renewal:
PUT /leases/{lease_id}/renew
Request: { "ttl": 3600 }
Response: the updated lease (with the same lease_id, new version, new expiration_time, status still ACTIVE)
Then, the client doesn't need to update the lease_id.
But note: if we update the same lease, then we are changing the lease's version and expiration. And we update the resource's current_version. So the lease remains the current lease.
So the flow for renewal:
current_lease = get_current_lease(resource_id) // returns the lease with the current version
if current_lease.lease_id != my_lease_id -> invalid (someone else took the lease)
renew_lease(my_lease_id, ttl)
But wait: what if between the get_current_lease and the renew, someone else took the lease? Then the renew will fail because we check that the lease is the current one (by comparing the resource's current_lease_id and the lease's version? Actually, in the renew transaction, we check:
resource.current_lease_id == given lease_id
lease.status == ACTIVE
And then we update the lease's version and expiration, and update the resource's current_version.
So if someone else took the lease in between, then the resource.current_lease_id would have changed, and the renew would fail.
So it's safe.
Now, what about the background job? It marks leases as EXPIRED if they are ACTIVE and expiration_time < now. But if we are renewing the lease, then the expiration_time is updated, so it won't be marked as EXPIRED.
And if the lease expires and we try to renew? The renew will fail because the lease status is not ACTIVE (it will be EXPIRED after the background job). So the client must handle that.
Now, let's adjust the create and renew to update the same lease for renew, and create a new lease for create (and for preemption).
So:
Create (with preemption):
- If there's an active lease, revoke it (set status=REVOKED) and update the resource's current_version (so that the old lease becomes invalid) and set current_lease_id to the new lease_id.
- Then create a new lease (new lease_id) and set the resource's current_lease_id to the new lease_id and current_version to the new version.
Renew:
- Update the same lease (same lease_id) and increment the version and update expiration_time.
Revoke:
- Set the lease status to REVOKED and update the resource's current_lease_id to null and current_version to current_version+1.
Then, for the check:
We have endpoint GET /resources/{resource_id}/lease that returns the current lease (if any).
And the client does:
current_lease = GET /resources/{resource_id}/lease
if current_lease is null -> invalid
if current_lease.lease_id != my_lease_id -> invalid
if current_lease.status != 'ACTIVE' -> invalid
if current_lease.expiration_time <= now() -> invalid
But note: what if the lease is ACTIVE and not expired, but the version changed? That cannot happen because if the version changed, we either renewed (same lease_id) or we created a new lease (then the lease_id would change). So if the lease_id is the same, the version change is okay because we don't check version.
However, we are not checking the version. But what if there's a bug and the resource's current_version is not the same as the lease's version? Then the lease might be invalid? But in our design, they are always the same when the lease is the current one.
So we are safe.
Now, let's write the API spec:
API:
POST /leases
Request:
{
"resource_id": "string",
"owner_id": "string",
"ttl": integer // in seconds
}
Response (201 Created):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": integer,
"expiration_time": "string (ISO8601)",
"status": "ACTIVE"
}
PUT /leases/{lease_id}/renew
Request:
{
"ttl": integer
}
Response (200 OK):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": integer, // incremented
"expiration_time": "string (ISO8601)",
"status": "ACTIVE"
}
PUT /leases/{lease_id}/revoke
Response (200 OK):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": integer, // incremented
"expiration_time": "string (ISO8601)", // unchanged
"status": "REVOKED"
}
GET /resources/{resource_id}/lease
Response (200 OK):
{
"lease_id": "uuid or null",
"owner_id": "string or null",
"version": integer or null,
"expiration_time": "string (ISO8601) or null",
"status": "string or null"
}
Then the client (resource manager) uses:
current = GET /resources/{resource_id}/lease
if current.lease_id is null -> no lease
else if current.lease_id != my_lease_id -> not valid (someone else has the lease)
else if current.status != 'ACTIVE' -> not valid
else if current.expiration_time <= now() -> not valid
else -> valid
But note: the expiration_time might be in the future but the lease might be ACTIVE and the version might be old? But we don't check version. However, if the version is old, that means the resource's current_version is not the same as the lease's version? But we are returning the lease that is the current_lease_id, so the lease's version must be the current_version. So we don't need to check version.
However, what if the lease is the current one but the version is not the same as the resource's current_version? That would be a data inconsistency. We can prevent that by always updating the lease's version and the resource's current_version in the same transaction.
So we are safe.
Now, the background jobs:
Job 1 (every minute):
UPDATE leases
SET status = 'EXPIRED'
WHERE status = 'ACTIVE'
AND expiration_time < now();
Job 2 (every day):
DELETE FROM leases
WHERE status IN ('EXPIRED', 'REVOKED')
AND updated_at < now() - interval '1 day';
We assume we have an `updated_at` column that is set on every update.
Also, we might want to index:
- resources: resource_id (primary key), current_lease_id (for join)
- leases: lease_id (primary key), resource_id (for finding leases by resource), status, expiration_time (for the background job)
We also need to handle the case where the same resource is being leased by two different owners at the same time? Our transaction with row-level locking (FOR UPDATE) should prevent that.
However, in a distributed system, we might have multiple instances of the lease service? Then we need a distributed lock or use a database that supports row-level locking across nodes? Actually, if we use a single database, then the row-level lock (SELECT ... FOR UPDATE) will work as long as all the lease service instances use the same database and the database supports row-level locking.
But if we have multiple lease service instances, we must ensure that they all use the same database and that the transactions are properly isolated.
Alternatively, we can use a distributed consensus algorithm (like Raft) to manage the leases. But for simplicity, we assume a single database with row-level locking.
However, if we have multiple lease service instances, we must be cautious of the transaction isolation level. We should use SERIALIZABLE or at least REPEATABLE READ to avoid phantom reads? Actually, we are updating the resource row and the lease row. We must lock the resource row first (to prevent two transactions from both seeing that the resource is free and then both trying to lease it). Then we update the resource and the lease.
So:
In create:
BEGIN TRANSACTION
SELECT * FROM resources WHERE resource_id = ? FOR UPDATE -- locks the resource row
-- then check current_lease_id and possibly lock the old lease (if exists) with SELECT ... FOR UPDATE
-- then insert new lease and update resource.
This should be safe.
Now, what about the resource manager? It must handle the case where the lease is revoked by someone else. It will detect that when it checks the current lease and sees that the lease_id is not its own.
Then, it should deallocate the resource.
But what if the resource manager is in the middle of using the resource when the lease is revoked? Then the next time it checks, it will see that the lease is invalid and stop using it. But what about the current operation? We need fencing.
Fencing: we want to prevent the old owner from continuing to use the resource after the lease is revoked.
How? The resource manager must check the lease before every operation? Or the resource itself (if it's a shared resource) must check with the lease service?
Actually, the resource manager is the one that uses the resource. It should check the lease before using the resource. But if it's in the middle of a long operation, it might have checked at the beginning and then the lease is revoked during the operation.
We can have the resource manager re-check the lease periodically? Or we can have a fencing token that changes on every lease change (the version). Then the resource (if it's something like a disk) can store the last version that wrote to it, and if a write comes with an old version, it rejects it.
However, if the resource manager is the only one that uses the resource, then it can check the lease before each operation and if the lease is invalid, it stops.
But if the resource is shared (like a file), then we need the resource itself to enforce the fencing.
Let's assume the resource is managed by a resource manager that is the only one that uses it. Then the resource manager can:
- Before starting an operation, check the lease (as above). If invalid, abort.
- During a long operation, it might re-check periodically? But that might be complex.
Alternatively, we can have the resource manager set a fence (like a token) in the resource when it starts using it, and then when the lease is revoked, the new owner sets a new fence. But then the old owner might still be using the old fence? We need the resource to check the fence on every operation.
But if the resource is a simple resource (like a VM), then the resource manager can just shut down the VM when the lease is revoked.
So it depends on the resource.
For our design, we assume the resource manager is responsible for checking the lease and stopping use if the lease is invalid.
We can also have an event system:
When a lease is revoked (or expired), the lease service publishes an event. The resource manager subscribes to these events and immediately deallocates the resource when it receives a revocation event for its lease.
But then we have to handle network partitions: what if the resource manager doesn't receive the event? It will eventually check the lease and find it invalid.
So we can do both:
- On every operation, check the lease (or periodically check if the operation is long).
- Subscribe to revocation events for faster reaction.
Now, let's write the API in OpenAPI? But the problem says "Design a leased resource API", so we can just describe the endpoints and the data model.
We have described the endpoints and the data model.
Now, let's consider edge cases:
1. What if the lease service crashes after creating a lease but before updating the resource? We are in a transaction, so it's atomic.
2. What if the resource manager crashes after acquiring a lease? Then the lease will expire after TTL, and the resource will be deallocated when the resource manager checks again (or when the revocation event is not received because it's down). But the lease will be revoked by the background job? Actually, the lease will expire and then the background job will mark it as EXPIRED. Then the resource manager, when it comes back, will see that the lease is EXPIRED and stop using the resource.
3. What if the resource manager renews the lease just before it expires? Then it's okay.
4. What if the resource manager tries to renew after the lease has expired? Then the renew will fail because the lease status is not ACTIVE (it's EXPIRED). So the resource manager must handle that and stop using the resource.
5. What if two resource managers try to lease the same resource at the same time? The transaction with row-level lock will serialize them. The first one will succeed, the second one will wait for the lock, then see that the resource is already leased and then fail (if we don't allow preemption) or preempt (if we allow). In our create endpoint, we allow preemption by default.
But note: in the create endpoint, we revoke the old lease and then create a new one. So the second one will preempt the first.
But what if two create requests come at the same time? They both will lock the resource row, then one will revoke the old lease (if any) and create a new lease. The other will then try to revoke the lease that was just created? Actually, the second transaction, after acquiring the lock, will see the current_lease_id (which might be the one created by the first transaction) and then revoke it and create a new lease. So the first one's lease will be revoked.
So we are allowing preemption and the last one wins.
But note: the first transaction might have already committed when the second one starts? Actually, the second transaction will wait for the lock. Then when it gets the lock, it will see the current_lease_id (which is the one from the first transaction) and then revoke it and create a new lease.
So the first lease is revoked by the second.
This is acceptable if we want last-write-wins.
Alternatively, we might want to reject the second request if there's already an active lease? Then we change the create endpoint to:
If there's an active lease, fail with 409 Conflict.
But the problem says "leased resource API with fencing", and preemption is a form of fencing? Actually, preemption is when a new lease is granted and the old one is revoked. That is a form of fencing because the old owner is fenced out.
So we can support both: we can have a flag in the create request to allow preemption or not.
But for simplicity, we'll always allow preemption.
Now, let's write the API spec in a structured way.
We'll use OpenAPI 3.0.
But since we are not required to write the full YAML, we can describe.
However, the problem says "Design", so we can write the endpoints and the data model.
Let's summarize:
Data Model:
Table: resources
resource_id (PK)
current_lease_id (FK to leases.lease_id, nullable)
current_version (integer)
Table: leases
lease_id (PK)
resource_id (FK to resources.resource_id)
owner_id (string)
version (integer)
expiration_time (datetime)
status (enum: ACTIVE, EXPIRED, REVOKED)
created_at (datetime)
updated_at (datetime)
Indexes:
resources: index on resource_id (PK), index on current_lease_id
leases: index on lease_id (PK), index on resource_id, index on (status, expiration_time) for the background job.
API:
1. Create Lease:
POST /leases
Request body:
{
"resource_id": "string",
"owner_id": "string",
"ttl": 3600
}
Response (201):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": 1,
"expiration_time": "2024-01-01T00:00:00Z",
"status": "ACTIVE"
}
2. Renew Lease:
PUT /leases/{lease_id}/renew
Request body:
{
"ttl": 3600
}
Response (200):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": 2,
"expiration_time": "2024-01-01T01:00:00Z",
"status": "ACTIVE"
}
3. Revoke Lease:
PUT /leases/{lease_id}/revoke
Response (200):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": 3,
"expiration_time": "2024-01-01T00:00:00Z",
"status": "REVOKED"
}
4. Get Current Lease for a Resource:
GET /resources/{resource_id}/lease
Response (200):
{
"lease_id": "uuid or null",
"owner_id": "string or null",
"version": integer or null,
"expiration_time": "string (ISO8601) or null",
"status": "string or null"
}
5. (Optional) Get Lease by ID:
GET /leases/{lease_id}
Response (200):
{
"lease_id": "uuid",
"resource_id": "string",
"owner_id": "string",
"version": integer,
"expiration_time": "string (ISO8601)",
"status": "string"
}
The resource manager will use endpoint 4 to check the current lease for a resource and compare with its own lease_id.
Now, the background jobs:
Job 1 (every minute):
UPDATE leases
SET status = 'EXPIRED'
WHERE status = 'ACTIVE'
AND expiration_time < now();
Job 2 (every day at 2 AM):
DELETE FROM leases
WHERE status IN ('EXPIRED', 'REVOKED')
AND updated_at < now() - interval '1 day';
We assume the database supports these.
Alternatively, we can have a TTL on the leases table? But we want to keep them for a day after expiration/revocation.
Now, let's consider the fencing:
The fencing is achieved by:
- The resource manager checks the current lease_id for the resource. If it's not the same as the lease_id it holds, then it stops using the resource.
- The lease service updates the current_lease_id when a new lease is granted (or when revoked, sets to null).
So if a lease is revoked (by someone else) or expires, the current_lease_id will change (or become null) and the resource manager will see that and stop.
But what if the resource manager doesn't check for a while? Then it might continue to use the resource even though the lease is revoked? That's a problem.
We can have the resource manager check before every operation? Or at least periodically.
Also, we can have the resource manager subscribe to events (via WebSocket or polling) to get immediate notification.
But for the API, we don't need to specify that.
This design should work.
However, note: the resource manager might have multiple resources. It must check each resource's lease.
Also, the resource manager might be the one that created the lease? Then it knows the lease_id for each resource.
But what if the resource manager is not the one that created the lease? Then it must get the lease_id from somewhere? Actually, the resource manager is the one that leases the resource, so it creates the lease and gets the lease_id.
So the resource manager stores for each resource: the lease_id.
Then, when it wants to use the resource, it checks the current lease for that resource and compares the lease_id.
Now, what about the TTL? The resource manager must renew the lease before it expires. It can do that by calling the renew endpoint with the lease_id.
But if the lease is about to expire, the resource manager should renew it. However, if the lease is already expired, the renew will fail.
So the resource manager must:
- Periodically check the lease (or before each operation) and if the lease is about to expire (say, within 10% of the TTL) then renew.
But note: the renew endpoint requires the lease_id. And the resource manager must have the lease_id.
So the resource manager must store the lease_id for each resource.
Now, let's think about the cleanup of resources:
The lease service doesn't manage the resources. It only tracks leases. The resource manager must deallocate the resource when the lease is invalid.
But what if the resource manager crashes and never deallocates? Then the resource might be leaked.
We can have a separate resource allocator that allocates resources when a lease is created and deallocates when the lease is revoked/expired.
But that's a separate service.
Our lease service only provides the leasing mechanism.
So, to summarize:
We have designed a lease service with:
- Create lease (with preemption)
- Renew lease
- Revoke lease
- Get current lease for a resource
And background jobs to mark expired leases and delete old ones.
And the fencing is achieved by having the resource manager check that the lease_id it holds matches the current_lease_id of the resource.
This should work.
Let's write the SQL for the create lease (with preemption) in a transaction:
BEGIN;
-- Lock the resource row
SELECT * FROM resources WHERE resource_id = :resource_id FOR UPDATE;
-- If there's a current lease, revoke it
UPDATE leases
SET status = 'REVOKED', updated_at = now()
WHERE lease_id = (SELECT current_lease_id FROM resources WHERE resource_id = :resource_id)
AND status = 'ACTIVE';
-- Create a new lease
INSERT INTO leases (lease_id, resource_id, owner_id, version, expiration_time, status, created_at, updated_at)
VALUES (:new_lease_id, :resource_id, :owner_id, :new_version, :expiration_time, 'ACTIVE', now(), now());
-- Update the resource
UPDATE resources
SET current_lease_id = :new_lease_id, current_version = :new_version, updated_at = now()
WHERE resource_id = :resource_id;
COMMIT;
But note: the version for the new lease is the old version + 1. We need to get the old version.
We can do:
We lock the resource, then we get the current_version:
SELECT current_version FROM resources WHERE resource_id = :resource_id FOR UPDATE;
Let old_version = current_version (or 0 if null).
Then new_version = old_version + 1.
But note: if there's no current lease, then current_version might be 0? We can set the resource's current_version to 0 initially.
Alternatively, we can set the resource's current_version to the lease's version when we assign a lease.
So:
Step:
resource = SELECT current_version, current_lease_id FROM resources WHERE resource_id = ? FOR UPDATE
old_version = resource.current_version
new_version = old_version + 1
if resource.current_lease_id is not null:
UPDATE leases SET status='REVOKED', updated_at=now() WHERE lease_id=resource.current_lease_id AND status='ACTIVE'
INSERT INTO leases (lease_id, resource_id, owner_id, version, expiration_time, status, created_at, updated_at)
VALUES (new_lease_id, resource_id, owner_id, new_version, expiration_time, 'ACTIVE', now(), now())
UPDATE resources SET current_lease_id=new_lease_id, current_version=new_version, updated_at=now() WHERE resource_id=resource_id
This is safe.
For renewal:
BEGIN;
-- Lock the resource and the lease
SELECT * FROM resources WHERE resource_id = (SELECT resource_id FROM leases WHERE lease_id = :lease_id) FOR UPDATE;
SELECT * FROM leases WHERE lease_id = :lease_id FOR UPDATE;
-- Check that the lease is the current one and active
IF (SELECT current_lease_id FROM resources WHERE resource_id = (SELECT resource_id FROM leases WHERE lease_id = :lease_id)) != :lease_id
OR (SELECT status FROM leases WHERE lease_id = :lease_id) != 'ACTIVE'
THEN ROLLBACK and return error.
-- Update the lease and the resource
UPDATE leases
SET expiration_time = :new_expiration, version = version + 1, updated_at = now()
WHERE lease_id = :lease_id;
UPDATE resources
SET current_version = current_version + 1, updated_at = now()
WHERE resource_id = (SELECT resource_id FROM leases WHERE lease_id = :lease_id);
COMMIT;
But note: we are updating the lease's version and the resource's current_version by 1. And we are using the same lease_id.
For revoke:
BEGIN;
-- Lock the resource and the lease
SELECT * FROM resources WHERE resource_id = (SELECT resource_id FROM leases WHERE lease_id = :lease_id) FOR UPDATE;
SELECT * FROM leases WHERE lease_id = :lease_id FOR UPDATE;
-- Check that the lease is the current one and active
IF (SELECT current_lease_id FROM resources WHERE resource_id = (SELECT resource_id FROM leases WHERE lease_id = :lease_id)) != :lease_id
OR (SELECT status FROM leases WHERE lease_id = :lease_id) != 'ACTIVE'
THEN ROLLBACK and return error.
-- Revoke the lease and update the resource
UPDATE leases
SET status = 'REVOKED', updated_at = now()
WHERE lease_id = :lease_id;
UPDATE resources
SET current_lease_id = NULL, current_version = current_version + 1, updated_at = now()
WHERE resource_id = (SELECT resource_id FROM leases WHERE lease_id = :lease_id);
COMMIT;
This design should work.
Now, the resource manager must handle the case where the lease is revoked by someone else. It will see that the current_lease_id is not its lease_id (or null) and stop.
But what if the resource manager is in the middle of an operation? It should check the lease before each operation? Or at least periodically.
We leave that to the resource manager.
This is the design.
Let me know if you have any questions.</think>