lokalise-rate-limits

0
1
Source

Implement Lokalise rate limiting, backoff, and request queuing patterns. Use when handling rate limit errors, implementing retry logic, or optimizing API request throughput for Lokalise. Trigger with phrases like "lokalise rate limit", "lokalise throttling", "lokalise 429", "lokalise retry", "lokalise backoff".

Install

mkdir -p .claude/skills/lokalise-rate-limits && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4702" && unzip -o skill.zip -d .claude/skills/lokalise-rate-limits && rm skill.zip

Installs to .claude/skills/lokalise-rate-limits

About this skill

Lokalise Rate Limits

Overview

Lokalise enforces a strict 6 requests per second rate limit across all API endpoints (https://api.lokalise.com/api2). Exceeding this triggers a 429 Too Many Requests response. This skill covers request queuing with 170ms minimum spacing, exponential backoff for 429 recovery, bulk operation throttling, and proactive quota monitoring via response headers.

Prerequisites

  • @lokalise/node-api SDK installed (npm install @lokalise/node-api)
  • API token configured (read or read/write scope depending on operations)
  • Node.js 18+ for native AbortController support in timeout handling

Instructions

1. Understand the Rate Limit Headers

Every Lokalise API response includes rate limit headers:

X-RateLimit-Limit: 6          # Max requests per second
X-RateLimit-Remaining: 4      # Requests remaining in current window
X-RateLimit-Reset: 1700000000 # Unix timestamp when the window resets
Retry-After: 1                # Seconds to wait (only on 429 responses)

Always read these headers. Never hardcode assumptions about the window — Lokalise may adjust limits per plan tier.

2. Implement a Request Queue with 170ms Spacing

Space requests at minimum 170ms apart (1000ms / 6 = ~167ms, rounded up). Use p-queue for concurrency control:

import PQueue from "p-queue";

const lokaliseQueue = new PQueue({
  concurrency: 1,
  interval: 170,
  intervalCap: 1,
});

async function queuedRequest<T>(fn: () => Promise<T>): Promise<T> {
  return lokaliseQueue.add(fn, { throwOnTimeout: true });
}

// Usage with the SDK
import { LokaliseApi } from "@lokalise/node-api";
const lokalise = new LokaliseApi({ apiKey: process.env.LOKALISE_API_TOKEN });

const keys = await queuedRequest(() =>
  lokalise.keys().list({
    project_id: "123456789.abcdefgh",
    limit: 500,
    page: 1,
  })
);

3. Add Exponential Backoff for 429 Recovery

When a 429 occurs, honor the Retry-After header first. If absent, use exponential backoff with jitter:

async function withBackoff<T>(
  fn: () => Promise<T>,
  maxRetries = 5
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error: any) {
      if (error.code === 429 && attempt < maxRetries) {
        const retryAfter = error.headers?.["retry-after"];
        const baseDelay = retryAfter
          ? parseInt(retryAfter, 10) * 1000
          : Math.pow(2, attempt) * 1000;
        const jitter = Math.random() * 500;
        const delay = baseDelay + jitter;

        console.warn(
          `Rate limited. Attempt ${attempt + 1}/${maxRetries}. ` +
          `Waiting ${Math.round(delay)}ms...`
        );
        await new Promise((resolve) => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
  throw new Error("Max retries exceeded for Lokalise API request");
}

4. Throttle Bulk Operations

For operations that process many items (listing all keys, bulk translations), paginate with built-in throttling:

async function paginateAll<T>(
  fetchPage: (page: number) => Promise<{ items: T[]; totalPages: number }>
): Promise<T[]> {
  const allItems: T[] = [];
  let page = 1;
  let totalPages = 1;

  do {
    const result = await queuedRequest(() => fetchPage(page));
    allItems.push(...result.items);
    totalPages = result.totalPages;
    page++;
  } while (page <= totalPages);

  return allItems;
}

// Fetch all keys across pages
const allKeys = await paginateAll(async (page) => {
  const response = await lokalise.keys().list({
    project_id: projectId,
    limit: 500, // max per page
    page,
  });
  return {
    items: response.items,
    totalPages: response.totalCount
      ? Math.ceil(response.totalCount / 500)
      : 1,
  };
});

For bulk key creation, batch into groups of 500 (API limit per request) and queue each batch:

async function bulkCreateKeys(
  projectId: string,
  keys: Array<{ key_name: string; platforms: string[] }>
): Promise<void> {
  const batchSize = 500;
  for (let i = 0; i < keys.length; i += batchSize) {
    const batch = keys.slice(i, i + batchSize);
    await queuedRequest(() =>
      lokalise.keys().create({
        project_id: projectId,
        keys: batch,
      })
    );
    console.log(
      `Created keys ${i + 1}-${Math.min(i + batchSize, keys.length)} ` +
      `of ${keys.length}`
    );
  }
}

5. Monitor Quota Proactively

Track remaining quota and preemptively slow down before hitting the limit:

let remainingRequests = 6;
let resetTimestamp = 0;

function updateQuota(headers: Record<string, string>): void {
  remainingRequests = parseInt(headers["x-ratelimit-remaining"] ?? "6", 10);
  resetTimestamp = parseInt(headers["x-ratelimit-reset"] ?? "0", 10);
}

async function throttleIfNeeded(): Promise<void> {
  if (remainingRequests <= 1) {
    const now = Math.floor(Date.now() / 1000);
    const waitSeconds = Math.max(0, resetTimestamp - now) + 0.5;
    console.warn(
      `Quota nearly exhausted (${remainingRequests} remaining). ` +
      `Pausing ${waitSeconds}s until reset.`
    );
    await new Promise((resolve) =>
      setTimeout(resolve, waitSeconds * 1000)
    );
  }
}

Output

  • Request queue enforcing 6 req/sec with 170ms minimum spacing between calls
  • Automatic retry with exponential backoff + jitter on 429 responses
  • Paginated fetching with throttling for bulk data retrieval
  • Proactive throttling when X-RateLimit-Remaining drops to 1

Error Handling

HeaderDescriptionAction
X-RateLimit-LimitMax requests per window (always 6)Use as concurrency ceiling
X-RateLimit-RemainingRequests left in current windowPause proactively when <= 1
X-RateLimit-ResetUnix timestamp of window resetSleep until this time on exhaustion
Retry-AfterSeconds to wait (only on 429)Always honor this value exactly

If you receive a 429 without Retry-After, default to 1 second then exponential backoff. Never retry more than 5 times — if consistently rate-limited, your architecture needs request consolidation, not more retries.

Examples

Complete Rate-Limited Client

import { LokaliseApi } from "@lokalise/node-api";
import PQueue from "p-queue";

class RateLimitedLokalise {
  private api: LokaliseApi;
  private queue: PQueue;

  constructor(apiKey: string) {
    this.api = new LokaliseApi({ apiKey });
    this.queue = new PQueue({ concurrency: 1, interval: 170, intervalCap: 1 });
  }

  async request<T>(fn: (api: LokaliseApi) => Promise<T>): Promise<T> {
    return this.queue.add(
      () => withBackoff(() => fn(this.api)),
      { throwOnTimeout: true }
    );
  }
}

// Usage
const client = new RateLimitedLokalise(process.env.LOKALISE_API_TOKEN!);
const keys = await client.request((api) =>
  api.keys().list({ project_id: "123456789.abcdefgh", limit: 500 })
);

CLI with Rate Limiting

# The lokalise2 CLI respects rate limits internally, but for scripted
# loops you need manual spacing:
for project_id in $(lokalise2 project list --token $TOKEN --format json \
  | jq -r '.[].project_id'); do
  lokalise2 file download \
    --token "$LOKALISE_API_TOKEN" \
    --project-id "$project_id" \
    --format json \
    --dest ./locales/"$project_id"/
  sleep 0.2  # 200ms spacing
done

Resources

Next Steps

For handling specific API errors beyond rate limits, see lokalise-common-errors.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

11240

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

9033

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

18828

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

5519

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,6851,428

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,2681,335

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,5391,148

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,357809

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,264728

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,489684