Understanding Instance States

Track your instance lifecycle through PROVISIONING, RUNNING, and DELETING states

Understanding Instance States

Track your Redis instance through its complete lifecycle. This guide explains each state, what's happening behind the scenes, and how to handle each phase.

The Three Instance States

Your SwiftCache Redis instance goes through exactly three states during its lifetime:

PROVISIONING

Status: Instance is being created and configured Duration: 30-60 seconds What's happening:

  • Your instance is allocated to a physical server in your chosen region (eu-central)
  • Redis is installed and configured with your requested memory limit
  • Network connectivity is being established
  • DNS hostname is being created (abc123.redis.swiftcache.io)
  • API keys are being bound to the instance

What you can do:

  • Check status via polling
  • View the instance in your dashboard
  • Cannot connect to Redis yet - it's not ready

Example response while PROVISIONING:

{
  "instance": {
    "id": "inst_abc123xyz",
    "name": "my-cache",
    "status": "PROVISIONING",
    "hostname": null,
    "maxMemoryMb": 512,
    "region": "eu-central",
    "tier": "dedicated",
    "createdAt": "2024-03-15T10:30:00Z"
  }
}

RUNNING

Status: Instance is ready for connections Duration: Until you delete it What's happening:

  • Provisioning completed successfully
  • Redis is fully operational and listening for connections
  • Your hostname is active and resolvable (dns is live)
  • API keys are bound and ready to use
  • Metrics collection is active

What you can do:

  • Connect via hostname and API key
  • Execute Redis commands
  • Monitor metrics
  • Scale memory up or down
  • Update configuration

Example response when RUNNING:

{
  "instance": {
    "id": "inst_abc123xyz",
    "name": "my-cache",
    "status": "RUNNING",
    "hostname": "abc123.redis.swiftcache.io",
    "maxMemoryMb": 512,
    "region": "eu-central",
    "tier": "dedicated",
    "createdAt": "2024-03-15T10:30:00Z",
    "apiKeys": [
      {
        "id": "key_def456",
        "name": "my-cache-default",
        "createdAt": "2024-03-15T10:30:00Z"
      }
    ]
  }
}

DELETING

Status: Instance is being permanently removed Duration: 10-30 seconds What's happening:

  • Deletion was initiated via DELETE request
  • Data is being wiped from the server
  • Infrastructure (Pod, Service, volumes) is being cleaned up
  • DNS is being deregistered
  • Instance will soon be completely removed from your account

What you can do:

  • Nothing - deletion is final and irreversible
  • View it briefly in dashboard with DELETING status
  • It will disappear within seconds

Important: Once deletion is initiated, you cannot cancel it. Make sure to back up any critical data before deleting.

Polling for Status Changes

When you create an instance, it starts in PROVISIONING state. You need to poll until it reaches RUNNING before you can use it.

Basic Polling Pattern

// Create instance
const createResponse = await fetch('https://api.swiftcache.io/api/v1/instances', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer sk_live_your_api_key_here'
  },
  body: JSON.stringify({
    organizationId: 'org_123',
    name: 'my-redis',
    maxMemory: 536870912, // 512MB in bytes
    region: 'eu-central'
  })
});

const { instance } = await createResponse.json();
const instanceId = instance.id;

// Poll until RUNNING
let isRunning = false;
let attempts = 0;
const maxAttempts = 120; // 2 minutes with 1-second intervals

while (!isRunning && attempts < maxAttempts) {
  const statusResponse = await fetch(
    `https://api.swiftcache.io/api/v1/instances/${instanceId}`,
    {
      headers: { 'Authorization': 'Bearer sk_live_your_api_key_here' }
    }
  );

  const { instance: statusInstance } = await statusResponse.json();

  if (statusInstance.status === 'RUNNING') {
    console.log('Instance ready!', statusInstance.hostname);
    isRunning = true;
  } else {
    console.log(`Status: ${statusInstance.status}, waiting...`);
    await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
  }

  attempts++;
}

if (!isRunning) {
  throw new Error('Instance provisioning timeout after 2 minutes');
}

Polling with Exponential Backoff

For production code, use exponential backoff to reduce load:

async function waitForInstanceReady(instanceId: string, apiKey: string): Promise<string> {
  let delay = 1000; // Start with 1 second
  const maxDelay = 10000; // Cap at 10 seconds
  const maxAttempts = 120;

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const response = await fetch(
      `https://api.swiftcache.io/api/v1/instances/${instanceId}`,
      {
        headers: { 'Authorization': `Bearer ${apiKey}` }
      }
    );

    if (!response.ok) {
      throw new Error(`API error: ${response.statusCode}`);
    }

    const { instance } = await response.json();

    if (instance.status === 'RUNNING') {
      return instance.hostname;
    }

    if (instance.status === 'PROVISIONING') {
      console.log(`Still provisioning... (attempt ${attempt + 1}/${maxAttempts})`);
      await new Promise(resolve => setTimeout(resolve, delay));
      delay = Math.min(delay * 1.5, maxDelay); // Increase delay
      continue;
    }

    // Unexpected status
    throw new Error(`Unexpected instance status: ${instance.status}`);
  }

  throw new Error('Provisioning timeout after 2 minutes');
}

// Usage
const hostname = await waitForInstanceReady('inst_abc123', 'sk_live_xxx');
console.log(`Connect to: ${hostname}`);

Python Polling Example

import time
import requests

def wait_for_instance(instance_id, api_key, timeout=120):
    """Poll until instance is RUNNING"""
    start = time.time()
    delay = 1

    while time.time() - start < timeout:
        response = requests.get(
            f'https://api.swiftcache.io/api/v1/instances/{instance_id}',
            headers={'Authorization': f'Bearer {api_key}'}
        )
        response.raise_for_status()

        instance = response.json()['instance']

        if instance['status'] == 'RUNNING':
            return instance['hostname']

        print(f"Status: {instance['status']}, waiting...")
        time.sleep(min(delay, 10))
        delay *= 1.5

    raise TimeoutError('Instance provisioning timeout')

# Usage
hostname = wait_for_instance('inst_abc123', 'sk_live_xxx')
print(f"Ready to connect: {hostname}")

State Transition Diagram

Created
  |
  v
PROVISIONING (30-60 seconds)
  |
  +-- Failure (rare)
  |     |
  |     v
  |   [Error state - contact support]
  |
  +-- Success
        |
        v
      RUNNING (hours/days/months)
        |
        +-- User initiates DELETE
        |     |
        |     v
        |   DELETING (10-30 seconds)
        |     |
        |     v
        |   [Completely removed]
        |
        +-- Account suspended/deleted
              |
              v
            [Instance auto-deleted]

Troubleshooting State Issues

Instance stuck in PROVISIONING

Problem: Instance has been PROVISIONING for more than 2 minutes

Causes:

  • Server capacity issue (rare)
  • Network connectivity problem
  • DNS propagation delay (normal, wait up to 5 minutes for global DNS)

Solutions:

  1. Wait longer (DNS can take up to 5 minutes globally)
  2. Check your internet connection
  3. Try a smaller memory size
  4. Delete and recreate the instance
  5. Contact support if issue persists
# Check if it's still provisioning (not failed)
curl -H "Authorization: Bearer sk_live_xxx" \
  https://api.swiftcache.io/api/v1/instances/inst_abc123

Cannot find instance after creation

Problem: Created instance but can't retrieve it

Likely cause: Using wrong organization ID or credentials

Solution:

# List all instances for your organization
curl -H "Authorization: Bearer sk_live_xxx" \
  'https://api.swiftcache.io/api/v1/instances?organizationId=org_correct_id'

Instance deleted unexpectedly

Problem: Instance was RUNNING but now shows as DELETING or gone

Causes:

  • Someone with admin access deleted it
  • Account reached usage limits
  • Account was suspended or closed

What to do:

  • Check if deletion was intentional (admins can delete without your knowledge in shared orgs)
  • Restore from backups if you have persistence enabled
  • For unexpected suspension, contact support

API Endpoints for State Checking

Get Current State

GET /api/v1/instances/:instanceId
Authorization: Bearer sk_live_your_api_key

# Response with all instance details including current status
{
  "instance": {
    "id": "inst_abc123",
    "status": "RUNNING",
    "hostname": "abc123.redis.swiftcache.io",
    ...
  }
}

List All Instances (shows all states)

GET /api/v1/instances?organizationId=org_123
Authorization: Bearer sk_live_your_api_key

# Response includes all instances in any state
{
  "instances": [
    { "id": "inst_abc123", "status": "RUNNING", ... },
    { "id": "inst_def456", "status": "PROVISIONING", ... },
    { "id": "inst_ghi789", "status": "DELETING", ... }
  ]
}

Delete Instance (triggers DELETING state)

DELETE /api/v1/instances/:instanceId
Authorization: Bearer sk_live_your_api_key

# Response: 202 Accepted
{
  "message": "Instance deletion initiated",
  "instance": {
    "id": "inst_abc123",
    "status": "DELETING"
  }
}

Best Practices

  1. Always poll after creation - Don't assume RUNNING immediately
  2. Use reasonable timeouts - 2 minutes is sufficient for PROVISIONING
  3. Handle state changes gracefully - Application should handle DELETING status
  4. Monitor in production - Check status periodically for unexpected DELETING
  5. Store hostname once RUNNING - Don't repeatedly fetch it, it won't change
  6. Back up before deleting - DELETING is permanent and immediate

Summary

Understanding instance states helps you:

  • Know when your Redis is ready for connections
  • Handle provisioning delays gracefully
  • Respond appropriately to deletion
  • Troubleshoot unexpected state changes

The key takeaway: Wait for RUNNING status before attempting to connect. The 30-60 second provisioning window is unavoidable, but polling properly makes it invisible to your users.