Introduction

Stateset Cloud is our fully managed platform that provides scalable infrastructure, secure APIs, and comprehensive tools for building and deploying autonomous business operations. This guide will walk you through the initial setup and configuration of your Stateset Cloud environment.

Prerequisites

Before you begin, ensure you have:

  • A Stateset account (sign up at stateset.com/signup)
  • Access to your email for verification
  • Basic understanding of REST APIs and authentication

Getting Started

1

Create a New Project

Navigate to the Stateset Cloud Dashboard and click the “New Project” button in the top right corner.

Configure your project with:

  • Project Name: A unique identifier for your project
  • Environment: Choose between Development, Staging, or Production
  • Region: Select your preferred data center location for optimal performance
2

Create Your Organization

Set up your organization to manage team members and billing:

  1. Click “New Organization” in the dashboard
  2. Enter your organization details:
    • Organization name
    • Industry type
    • Company size
  3. Configure team settings and invite team members
3

Generate API Keys

Create API keys to authenticate your applications:

  1. Navigate to Settings > API Keys
  2. Click “New API Key”
  3. Configure key permissions:
    • Read/Write access levels
    • Scope restrictions (if needed)
    • Expiration settings
  4. Securely store your API key - it won’t be shown again

Core Features

Infrastructure Management

Stateset Cloud provides:

  • Auto-scaling: Automatically adjusts resources based on demand
  • Global CDN: Ensures fast response times worldwide
  • Database Management: Fully managed PostgreSQL with automatic backups
  • Event Streaming: Real-time event processing with Kafka

Security & Compliance

  • SOC 2 Type II Certified: Enterprise-grade security standards
  • Data Encryption: AES-256 encryption at rest and in transit
  • RBAC: Role-based access control for team management
  • Audit Logs: Complete activity tracking for compliance

Monitoring & Analytics

  • Real-time Dashboards: Monitor API usage, performance metrics, and costs
  • Custom Alerts: Set up notifications for important events
  • Log Management: Centralized logging with search and filtering

Environment Configuration

Development Environment

// .env.development
STATESET_API_KEY=your_development_api_key
STATESET_API_URL=https://api.stateset.com/v1
STATESET_ENVIRONMENT=development

Production Environment

// .env.production
STATESET_API_KEY=your_production_api_key
STATESET_API_URL=https://api.stateset.com/v1
STATESET_ENVIRONMENT=production
STATESET_LOG_LEVEL=error

Quick Integration Example

Here’s a simple example to verify your Stateset Cloud setup:

const { StateSetClient } = require('stateset-node');

// Initialize the client
const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  environment: process.env.STATESET_ENVIRONMENT
});

// Test the connection
async function testConnection() {
  try {
    const health = await client.health.check();
    console.log('Connection successful:', health);
    
    // Create a test order
    const order = await client.orders.create({
      customer_email: 'test@example.com',
      items: [{
        sku: 'TEST-001',
        quantity: 1,
        price: 99.99
      }]
    });
    
    console.log('Test order created:', order.id);
  } catch (error) {
    console.error('Connection failed:', error);
  }
}

testConnection();

Best Practices

API Key Management

  • Never commit API keys to version control
  • Use environment variables for key storage
  • Rotate keys regularly
  • Use separate keys for different environments

Rate Limiting

  • Default rate limit: 1000 requests per minute
  • Implement exponential backoff for retries
  • Use webhook endpoints for async operations

Error Handling

try {
  const response = await client.orders.list();
  // Process response
} catch (error) {
  if (error.status === 429) {
    // Handle rate limiting
    await sleep(error.retryAfter * 1000);
  } else if (error.status >= 500) {
    // Handle server errors
    console.error('Server error:', error.message);
  }
}

Support Resources

Advanced Configuration

Rate Limiting and Retry Strategies

Implement robust retry logic to handle API rate limits and transient failures:

class StateSetApiClient {
  constructor(apiKey, options = {}) {
    this.apiKey = apiKey;
    this.maxRetries = options.maxRetries || 3;
    this.retryDelay = options.retryDelay || 1000;
    this.rateLimiter = new RateLimiter({
      tokensPerInterval: 100,
      interval: 'minute'
    });
  }

  async makeRequest(endpoint, options = {}) {
    let lastError;
    
    for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
      try {
        // Check rate limit
        await this.rateLimiter.removeTokens(1);
        
        const response = await fetch(`${STATESET_API_URL}${endpoint}`, {
          ...options,
          headers: {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json',
            ...options.headers
          }
        });

        // Handle rate limit response
        if (response.status === 429) {
          const retryAfter = response.headers.get('Retry-After');
          const delay = retryAfter ? parseInt(retryAfter) * 1000 : this.calculateBackoff(attempt);
          
          console.warn(`Rate limited. Retrying after ${delay}ms...`);
          await this.sleep(delay);
          continue;
        }

        // Handle other errors
        if (!response.ok) {
          const error = await response.json();
          throw new StateSetApiError(error.message, response.status, error.code);
        }

        return await response.json();
        
      } catch (error) {
        lastError = error;
        
        // Don't retry on client errors (4xx)
        if (error.status >= 400 && error.status < 500 && error.status !== 429) {
          throw error;
        }
        
        // Calculate exponential backoff
        if (attempt < this.maxRetries) {
          const delay = this.calculateBackoff(attempt);
          console.warn(`Request failed, retrying in ${delay}ms...`, error.message);
          await this.sleep(delay);
        }
      }
    }
    
    throw lastError || new Error('Max retries exceeded');
  }

  calculateBackoff(attempt) {
    // Exponential backoff with jitter
    const baseDelay = this.retryDelay * Math.pow(2, attempt);
    const jitter = Math.random() * 1000;
    return Math.min(baseDelay + jitter, 30000); // Max 30 seconds
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

// Custom error class for better error handling
class StateSetApiError extends Error {
  constructor(message, status, code) {
    super(message);
    this.name = 'StateSetApiError';
    this.status = status;
    this.code = code;
  }
}

Connection Pooling and Performance

Optimize API performance with connection pooling and request batching:

class StateSetBatchClient extends StateSetApiClient {
  constructor(apiKey, options = {}) {
    super(apiKey, options);
    this.batchQueue = [];
    this.batchSize = options.batchSize || 50;
    this.batchInterval = options.batchInterval || 100;
    this.startBatchProcessor();
  }

  // Queue requests for batch processing
  async batchRequest(operation, data) {
    return new Promise((resolve, reject) => {
      this.batchQueue.push({
        operation,
        data,
        resolve,
        reject,
        timestamp: Date.now()
      });
    });
  }

  startBatchProcessor() {
    setInterval(async () => {
      if (this.batchQueue.length === 0) return;
      
      // Process up to batchSize items
      const batch = this.batchQueue.splice(0, this.batchSize);
      
      try {
        const response = await this.makeRequest('/batch', {
          method: 'POST',
          body: JSON.stringify({
            operations: batch.map(item => ({
              operation: item.operation,
              data: item.data
            }))
          })
        });

        // Resolve individual promises
        batch.forEach((item, index) => {
          if (response.results[index].error) {
            item.reject(new Error(response.results[index].error));
          } else {
            item.resolve(response.results[index].data);
          }
        });
      } catch (error) {
        // Reject all promises in the batch
        batch.forEach(item => item.reject(error));
      }
    }, this.batchInterval);
  }
}

Troubleshooting

Common Issues and Solutions

Debug Mode

Enable debug mode to troubleshoot issues:

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  debug: true, // Enables detailed logging
  logger: {
    info: (msg, data) => console.log('[INFO]', msg, data),
    warn: (msg, data) => console.warn('[WARN]', msg, data),
    error: (msg, data) => console.error('[ERROR]', msg, data)
  }
});

// Log all requests and responses
client.on('request', (req) => {
  console.log('Request:', {
    method: req.method,
    url: req.url,
    headers: req.headers
  });
});

client.on('response', (res) => {
  console.log('Response:', {
    status: res.status,
    headers: res.headers,
    data: res.data
  });
});

Monitoring and Alerts

Set Up Health Checks

Monitor your Stateset Cloud integration health:

class StateSetHealthMonitor {
  constructor(client, options = {}) {
    this.client = client;
    this.checkInterval = options.checkInterval || 60000; // 1 minute
    this.alertThreshold = options.alertThreshold || 3;
    this.failureCount = 0;
  }

  start() {
    setInterval(async () => {
      try {
        const health = await this.checkHealth();
        
        if (!health.healthy) {
          this.failureCount++;
          
          if (this.failureCount >= this.alertThreshold) {
            await this.sendAlert({
              type: 'service_unhealthy',
              message: `Stateset API unhealthy for ${this.failureCount} consecutive checks`,
              details: health
            });
          }
        } else {
          this.failureCount = 0;
        }
        
        // Log metrics
        await this.logMetrics({
          timestamp: new Date(),
          healthy: health.healthy,
          latency: health.latency,
          services: health.services
        });
        
      } catch (error) {
        console.error('Health check failed:', error);
        this.failureCount++;
      }
    }, this.checkInterval);
  }

  async checkHealth() {
    const start = Date.now();
    
    try {
      const response = await this.client.health.check();
      const latency = Date.now() - start;
      
      return {
        healthy: response.status === 'healthy',
        latency,
        services: response.services,
        timestamp: new Date()
      };
    } catch (error) {
      return {
        healthy: false,
        error: error.message,
        timestamp: new Date()
      };
    }
  }

  async sendAlert(alert) {
    // Integrate with your alerting system
    // Example: PagerDuty, Slack, email, etc.
    console.error('ALERT:', alert);
  }

  async logMetrics(metrics) {
    // Send to your metrics system
    // Example: Datadog, CloudWatch, Prometheus
    console.log('Metrics:', metrics);
  }
}

// Start monitoring
const monitor = new StateSetHealthMonitor(client);
monitor.start();

Next Steps

Now that you have your Stateset Cloud environment set up with robust error handling and monitoring: