Stock API Update Guide

Learn how to migrate to the new stock API.

Overview

We've upgraded our stock management system to use Redis Sorted Sets for improved performance, reliability, and atomic operations. This document outlines the changes and how to adapt your integration to the new system.

Key Changes

  1. Storage Model: Stocks are now stored in Redis Sorted Sets using the pattern stock:${ownerId}:${game}:${groupId}
  2. Atomic Operations: All stock checkout operations are now atomic using Redis Lua scripts
  3. Return Values: Response formats have been updated to better represent stock availability
  4. Error Handling: More detailed error responses for stock availability issues

API Endpoint Changes

GET /stock - Get Available Stocks

What Changed:

  • Response structure now reflects Redis Sorted Set counts by game and amount
  • No longer returns individual stock IDs in the response

Before:

{
  "stocks": {
    "FREE_FIRE": {
      "100": {
        "amount": 100,
        "stockLen": 5,
        "stockIds": [123, 124, 125, 126, 127],
        "usedAsBackupIds": []
      }
    }
  },
  "stockAccounts": { ... }
}

After:

{
  "stocks": {
    "FREE_FIRE": {
      "100": 5  // 5 stocks of amount 100 available
    }
  },
  "stockAccounts": { ... }
}

POST /stock/check - Check Stock Availability

What Changed:

  • Now uses atomic operations with Redis Sorted Sets to check availability
  • Response format updated to include more precise missing stock information

Before:

{
  "available": true,
  "stock": [
    {
      "amount": 100,
      "stock_id": 123
    }
  ]
}

After:

{
  "available": true,
  "missing": null  // If stocks not available, contains object of missing amounts
}

Error Example:

{
  "available": false,
  "missing": {
    "100": 2,  // Need 2 more of amount 100
    "50": 1    // Need 1 more of amount 50
  }
}

POST /stock/buy - Buy Stocks

What Changed:

  • Now uses atomic Lua scripts to ensure all-or-nothing stock checkout
  • Improved rollback mechanism if PostgreSQL update fails
  • More detailed response about purchased stocks

Before & After: The response structure remains similar but the operation is more reliable:

{
  "available": true,
  "quantity": 3,
  "codes": [
    {
      "id": 123,
      "code": {
        "amount": 100,
        "serial": "ABCD-1234-EFGH-5678"
      },
      "codeType": "UNIPIN_VOUCHER",
      "game": "FREE_FIRE"
    }
  ]
}

Integration Guidelines

Checking Stock Availability

When checking stock availability, focus on the available boolean and missing object:

// Example: Check if stocks are available
async function checkStockAvailability(game, amounts, quantity = 1) {
  const response = await fetch('/stock/check', {
    method: 'POST',
    body: JSON.stringify({
      game,
      combination: amounts,
      quantity
    }),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    }
  });
  
  const data = await response.json();
  
  if (data.available) {
    console.log('All requested stock is available');
    return true;
  } else {
    console.log('Missing stock quantities:', data.missing);
    return false;
  }
}

Buying Stocks

The buying process is now fully atomic - either all stocks are acquired or none:

// Example: Buy stocks
async function buyStocks(game, amounts, quantity = 1) {
  const response = await fetch('/stock/buy', {
    method: 'POST',
    body: JSON.stringify({
      game,
      combination: amounts,
      quantity
    }),
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    }
  });
  
  if (response.status === 200) {
    const data = await response.json();
    console.log(`Successfully purchased ${data.quantity} stocks`);
    return data.codes;
  } else {
    const error = await response.json();
    console.error('Failed to purchase stocks:', error);
    throw new Error('Stock purchase failed');
  }
}

Benefits of the New System

  1. Improved Performance: Redis Sorted Sets provide O(log(N)) complexity for range operations
  2. Atomic Operations: Prevents race conditions during high-concurrency checkout
  3. Better Reliability: Automatic rollback if any part of the transaction fails
  4. Increased Scalability: Designed for high throughput and concurrent access

Potential Migration Issues

  1. Different Response Format: Update your code to handle the new JSON response structures
  2. More Specific Errors: Error responses now contain more detailed information about missing stock
  3. All-or-Nothing Transactions: The system will not partially fulfill orders if insufficient stock exists

Best Practices

  1. Always Check Before Buying: While the buy operation is atomic, it's still good practice to check availability first
  2. Handle Missing Stock Gracefully: Use the detailed missing object to inform users which stock items are unavailable
  3. Implement Proper Error Handling: The API now provides more specific error details to help diagnose issues

Need Help?

If you encounter any issues during migration or have questions about the new system, please contact our support team at [email protected] or open a ticket in our developer portal.

On this page