## Intro

Kubernetes Leases are a coordination primitive that let components claim and renew ownership of a shared resource for a limited time. The control plane uses them for leader election in components like kube-controller-manager and kube-scheduler, and the node lifecycle controller relies on them for node heartbeats. Despite their critical role, Leases are often overlooked until something goes wrong. Setting up a local lab gives you a safe, repeatable environment to understand how they work, test failure scenarios, and build operational confidence.

This guide walks through creating a practical Kubernetes Lease local lab. You will learn how to set up a minimal Kubernetes environment, create and inspect Lease objects, simulate holder crashes, and recover from expired Leases. By the end, you will have a solid foundation for troubleshooting Lease-related issues in production and for developing custom controllers that use Leases for leader election.

## Version and Environment Inventory

Before you begin, establish the versions and topology of your lab. This ensures reproducibility and avoids surprises from API differences.

### Prerequisites

- **Kubernetes cluster**: A local single-node cluster is sufficient. We use kind (Kubernetes in Docker) for its simplicity, but minikube or k3s work equally well.
- **kubectl**: The Kubernetes command-line tool, version matching or newer than the cluster.
- **A text editor** for creating YAML manifests.
- **Basic understanding** of Kubernetes API resources and kubectl.

### Version Check

Run the following commands to verify your tools:

```bash
kubectl version --client
kind version
```

Expected output (example):

```text
Client Version: v1.29.1
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
kind v0.22.0 go1.21.6 linux/amd64
```

### Environment Topology

For this lab, we assume:

- One Kubernetes cluster running locally.
- The Lease API is available in the `coordination.k8s.io/v1` group (stable since Kubernetes 1.14).
- You have cluster-admin permissions in your local cluster (default in kind).

Check that the Lease API is available:

```bash
kubectl api-resources | grep leases
```

Expected output:

```text
leases   coordination.k8s.io/v1   true   Lease
```

## Safe Configuration Path

Now we will set up a scoped environment for Lease experiments. To avoid interfering with system components, we will create a dedicated namespace and use a service account with restricted permissions.

### Step 1: Create a Namespace and Service Account

Create a namespace called `lease-lab`:

```bash
kubectl create namespace lease-lab
```

Expected output:

```text
namespace/lease-lab created
```

Create a service account `lease-tester` in that namespace:

```bash
kubectl create serviceaccount lease-tester -n lease-lab
```

Expected output:

```text
serviceaccount/lease-tester created
```

### Step 2: Define Minimal RBAC for Lease Operations

Create a Role that allows full control over Leases in the namespace. Save the following as `lease-role.yaml`:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: lease-lab
  name: lease-manager
rules:
- apiGroups: ["coordination.k8s.io"]
  resources: ["leases"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
```

Apply the role:

```bash
kubectl apply -f lease-role.yaml
```

Expected output:

```text
role.rbac.authorization.k8s.io/lease-manager created
```

Create a RoleBinding to bind the Role to the service account. Save as `lease-rolebinding.yaml`:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: lease-lab
  name: lease-tester-binding
subjects:
- kind: ServiceAccount
  name: lease-tester
  namespace: lease-lab
roleRef:
  kind: Role
  name: lease-manager
  apiGroup: rbac.authorization.k8s.io
```

Apply the binding:

```bash
kubectl apply -f lease-rolebinding.yaml
```

Expected output:

```text
rolebinding.rbac.authorization.k8s.io/lease-tester-binding created
```

### Step 3: Create a Sample Lease Object

Create a Lease named `my-lease` in the `lease-lab` namespace. A Lease requires a `spec.holderIdentity` and a `spec.leaseDurationSeconds`. Optionally, set `spec.renewTime` and `spec.acquireTime`.

Example manifest (`lease.yaml`):

```yaml
apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
  name: my-lease
  namespace: lease-lab
spec:
  holderIdentity: "node-1"
  leaseDurationSeconds: 40
  acquireTime: "2023-10-01T12:00:00Z"
  renewTime: "2023-10-01T12:00:00Z"
  leaseTransitions: 0
```

Apply the manifest:

```bash
kubectl apply -f lease.yaml
```

Expected output:

```text
lease.coordination.k8s.io/my-lease created
```

## Verification and Diagnostics

Now verify that the Lease behaves as expected. We will inspect the object, simulate renewals, and check status fields.

### Inspect the Lease Object

Use `kubectl get` to see the Lease in YAML form:

```bash
kubectl get lease my-lease -n lease-lab -o yaml
```

Expected output (truncated):

```yaml
apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
  name: my-lease
  namespace: lease-lab
  ...
spec:
  holderIdentity: node-1
  leaseDurationSeconds: 40
  acquireTime: "2023-10-01T12:00:00Z"
  renewTime: "2023-10-01T12:00:00Z"
  leaseTransitions: 0
```

Check the holder identity:

```bash
kubectl get lease my-lease -n lease-lab -o jsonpath='{.spec.holderIdentity}'
```

Expected output:

```text
node-1
```

### Simulate a Renewal

A holder renews a Lease by updating the `renewTime` and optionally bumping `leaseTransitions`. Use `kubectl patch` to simulate a renewal:

```bash
kubectl patch lease my-lease -n lease-lab --type merge -p '{"spec":{"renewTime":"2023-10-01T12:00:20Z"}}'
```

Expected output:

```text
lease.coordination.k8s.io/my-lease patched
```

View the updated `renewTime`:

```bash
kubectl get lease my-lease -n lease-lab -o jsonpath='{.spec.renewTime}'
```

Expected output:

```text
2023-10-01T12:00:20Z
```

### Watch Lease Changes

To observe changes in real time, use `kubectl get --watch` in a separate terminal:

```bash
kubectl get lease my-lease -n lease-lab --watch
```

In another terminal, patch the Lease again and you will see the updated line appear.

## Failure Modes and Recovery

Understanding failure modes is critical. We will simulate a holder crash, observe Lease expiry, and practice recovery by assigning a new holder.

### Simulate a Holder Crash

Stop renewing the Lease. After `leaseDurationSeconds` (40 seconds in our example), the Lease is considered expired by other components, but the object remains with stale data. In a real system, a new candidate would attempt to acquire it.

### Simulate a New Holder Acquisition

To simulate a new holder taking over, update the `holderIdentity`, set `acquireTime` to the current time, `renewTime` to the current time, and increment `leaseTransitions` by 1.

First, get the current time in RFC3339 format:

```bash
NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
```

Then patch the Lease:

```bash
kubectl patch lease my-lease -n lease-lab --type merge -p "{\"spec\":{\"holderIdentity\":\"node-2\",\"acquireTime\":\"$NOW\",\"renewTime\":\"$NOW\",\"leaseTransitions\":1}}"
```

Expected output:

```text
lease.coordination.k8s.io/my-lease patched
```

Verify the transition:

```bash
kubectl get lease my-lease -n lease-lab -o yaml
```

Look for `holderIdentity: node-2` and `leaseTransitions: 1`.

### Rollback and Recovery

If you need to roll back a faulty update, you can use the Lease's `managedFields` or maintain a backup of the YAML. For quick recovery, save a copy before making changes:

```bash
kubectl get lease my-lease -n lease-lab -o yaml > lease-backup.yaml
```

To restore from backup:

```bash
kubectl apply -f lease-backup.yaml
```

Note: Applying may not overwrite all fields if `resourceVersion` conflicts occur; delete and recreate if necessary.

## Common Pitfalls and How to Avoid Them

Working with Leases can lead to subtle mistakes. Here are the most common pitfalls, why they happen, and how to avoid or recover from them.

### Using the Wrong API Group or Version

**Why it happens**: Older documentation or examples may reference `coordination.k8s.io/v1beta1`. That version was deprecated and removed in Kubernetes 1.22.

**How to avoid**: Always use `coordination.k8s.io/v1`. Verify with `kubectl api-resources | grep leases` before writing manifests.

**Recovery**: If you applied a v1beta1 Lease and the API is gone, delete the old object and recreate it as v1.

### Not Setting a Realistic leaseDurationSeconds

**Why it happens**: If the duration is too short, the holder may lose the Lease before it can renew, causing flapping and unnecessary transitions. If too long, failure detection slows down.

**How to avoid**: Choose a duration based on your renew loop interval. A common pattern is to set `leaseDurationSeconds` to at least 2-3 times the renew interval. For manual testing, 40 seconds works well.

**Recovery**: Patch the Lease with a longer duration:

```bash
kubectl patch lease my-lease -n lease-lab --type merge -p '{"spec":{"leaseDurationSeconds":120}}'
```

### Ignoring leaseTransitions

**Why it happens**: New holders forget to increment `leaseTransitions`. Observers use this field to detect that a new holder took over. If it stays at 0, it may look like the same holder is still active.

**How to avoid**: Always increment `leaseTransitions` when changing `holderIdentity`. If you use client libraries, they should do this automatically, but manual patches must include it.

**Recovery**: Patch the Lease to set the correct transition count:

```bash
kubectl patch lease my-lease -n lease-lab --type merge -p '{"spec":{"leaseTransitions":2}}'
```

### Using Static Times in Manifests

**Why it happens**: Copying an example with hardcoded times like `2023-10-01T12:00:00Z` leads to confusion when the current time differs. The Lease may appear expired immediately.

**How to avoid**: Always use the current time when creating or updating a Lease. In shell, use `date -u +"%Y-%m-%dT%H:%M:%SZ"`. In client code, use `metav1.Now()` or `time.Now()`.

**Recovery**: Patch the Lease with fresh times as shown earlier.

### Forgetting to Clean Up Namespaces

**Why it happens**: Leases are lightweight, so many developers leave test Leases behind, cluttering the cluster and potentially confusing future experiments.

**How to avoid**: Always delete the namespace at the end of a lab session: `kubectl delete namespace lease-lab`.

**Recovery**: If you forget, simply delete the namespace later; it removes all resources inside it.

## Operations Checklist

Use this checklist for safe and repeatable Lease operations in your lab. Assign a single accountable owner for each step in a team setting; for solo work, you are the owner. Revisit this checklist monthly or whenever you modify your Lease handling code.

| Step | Description | Command / Check | Expected Result | Owner | Review Frequency |
|------|-------------|-----------------|-----------------|-------|------------------|
| 1 | Verify environment | `kubectl version --client` and `kind version` | Versions match requirements | Platform Engineer (e.g., Alex Chen) | Monthly |
| 2 | Create namespace | `kubectl create namespace lease-lab` | Namespace created | Platform Engineer | Per lab session |
| 3 | Create RBAC | Apply role and rolebinding | Service account has minimal permissions | Security Lead (e.g., Maria Lopez) | Quarterly |
| 4 | Create a Lease | Apply lease manifest | Lease object exists | Developer (e.g., Priya Shah) | Per lab session |
| 5 | Inspect Lease | `kubectl get lease my-lease -n lease-lab -o yaml` | Holder identity set | Developer | Per lab session |
| 6 | Test renewal | Patch `renewTime` | `renewTime` updates | Developer | Per lab session |
| 7 | Simulate holder change | Patch `holderIdentity` and `transitions` | New holder recorded | Developer | Per lab session |
| 8 | Backup before changes | `kubectl get lease ... -o yaml > backup.yaml` | Backup file created | Developer | Per lab session |
| 9 | Restore if needed | Apply backup manifest | Original state restored | Developer | Per lab session |
| 10 | Clean up | `kubectl delete namespace lease-lab` | All resources removed | Platform Engineer | Per lab session |

## Conclusion

You now have a functional Kubernetes Lease local lab. You learned how to set up a scoped environment, create and manipulate Lease objects, verify their behavior, simulate failures, and recover. This lab provides a safe playground for exploring Lease semantics, testing leader election patterns, and developing custom controllers that rely on Leases.

Next steps:

- Experiment with Lease `preferredHolder` and `strategy` fields.
- Observe how `kube-controller-manager` uses Leases for leader election by inspecting the `kube-system` namespace.
- Build a small application that uses the Kubernetes client library to acquire and renew a Lease.

Remember, the first useful pilot should be narrow and measurable. This lab is a perfect foundation for deeper learning and safe experimentation before touching production.