concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore

concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore is a cursor rule for Cursor from PaulJPhilp/EffectPatterns. It costs 1,020 tokens per session, scanned A, original, MIT.

A TypeScript pattern that uses a semaphore—a counter limiting how many tasks may run at once—to control access to shared resources.

In plain words
What is it for?
Use it when limiting database connections, API calls, file work, or other concurrent operations in an Effect-TS program.
Why use it?
It prevents too many database queries or other operations from running simultaneously and exhausting the resource. It also gives waiting tasks a fair chance to proceed.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

Good fit Use it when limiting database connections, API calls, file work, or other…

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/pauljphilp/effectpatterns/concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/PaulJPhilp/EffectPatterns

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore

README.md
[![agentmods](https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore.svg)](https://agentmods.dev/rules/pauljphilp/effectpatterns/concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore)
Your own site
<a href="https://agentmods.dev/rules/pauljphilp/effectpatterns/concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore"><img src="https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore.svg" alt="Measured on agentmods" height="20"></a>
Per session 1,020 This file is loaded in full into every session.
When invoked 1,020 The same file — it is already loaded in full.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.01020 $0.01020
Opus 5 $0.00510 $0.00510
Sonnet 5 $0.00204 $0.00204
Haiku 4.5 $0.00102 $0.00102

Measured 7d ago against content hash d112bb19ca99, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-06, from the pricing page.

Security

Grade A, and why

concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 7d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

content/published/rules/cursor/concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore.mdc · 157 lines

How it starts

The opening of the file, as written. The whole thing — 157 lines — stays where its author put it; the contents beside it link to each section on GitHub.

description: Use Semaphore to limit concurrent access to resources, preventing overload and enabling fair resource distribution. globs: "**/*.ts" alwaysApply: true

Concurrency Pattern 2: Rate Limit Concurrent Access with Semaphore

Rule: Use Semaphore to limit concurrent access to resources, preventing overload and enabling fair resource distribution.

Example

This example demonstrates limiting concurrent database connections using a Semaphore, preventing connection pool exhaustion.

import { Effect, Semaphore, Fiber } from "effect";

interface QueryResult {
  readonly id: number;
  readonly result: string;
  readonly duration: number;
}

// Simulate a database query that holds a connection
const executeQuery = (
  queryId: number,
  connectionId: number,
  durationMs: number
): Effect.Effect<QueryResult> =>
  Effect.gen(function* () {
    const startTime = Date.now();

    yield* Effect.log(
      `[Query ${queryId}] Using connection ${connectionId}, duration: ${durationMs}ms`
    );

    // Simulate query execution
    yield* Effect.sleep(`${durationMs} millis`);

    const duration = Date.now() - startTime;

    return {
      id: queryId,
      result: `Result from query ${queryId}`,
      duration,
    };
  });

// Pool configuration
interface ConnectionPoolConfig {
  readonly maxConnections: number;
  readonly queryTimeout?: number;
}

// Create a rate-limited query executor
const createRateLimitedQueryExecutor = (
  config: ConnectionPoolConfig
): Effect.Effect<
  (queryId: number, durationMs: number) => Effect.Effect<QueryResult>
> =>
  Effect.gen(function* () {
    const semaphore = yield* Semaphore.make(config.maxConnections);
    let connectionCounter = 0;

    return (queryId: number, durationMs: number) =>
      Effect.gen(function* () {
        // Acquire a permit (wait if none available)
        yield* Semaphore.acquire(semaphore);

        const connectionId = ++connectionCounter;

        // Use try-finally to ensure permit is released
        const result = yield* executeQuery(queryId, connectionId, durationMs).pipe(
          Effect.ensuring(
            Semaphore.release(semaphore).pipe(
              Effect.tap(() =>
                Effect.log(`[Query ${queryId}] Released connection ${connectionId}`)
              )
            )
          )
        );

        return result;
      });
  });

// Simulate multiple queries arriving
const program = Effect.gen(function* () {
  const executor = yield* createRateLimitedQueryExecutor({
    maxConnections: 3, // Only 3 concurrent connections
  });

  // Generate 10 queries with varying durations
  const queries = Array.from({ length: 10 }, (_, i) => ({
    id: i + 1,
    duration: 500 + Math.random() * 1500, // 500-2000ms
  }));

  console.log(`\n[POOL] Starting with max 3 concurrent connections\n`);

  // Execute all queries with concurrency limit
  const results = yield* Effect.all(
    queries.map((q) =>
      executor(q.id, Math.round(q.duration)).pipe(Effect.fork)
    )
  ).pipe(
    Effect.andThen((fibers) =>
      Effect.all(fibers.map((fiber) => Fiber.join(fiber)))
    )
  );

  console.log(`\n[POOL] All queries completed\n`);

  // Summary
  const totalDuration = results.reduce((sum, r) => sum + r.duration, 0);
  const avgDuration = totalDuration / results.length;

  console.log(`[SUMMARY]`);
  console.log(`  Total queries: ${results.length}`);
  console.log(`  Avg duration: ${Math.round(avgDuration)}ms`);
  console.log(`  Total time: ${Math.max(...results.map((r) => r.duration))}ms (parallel)`);
});

Effect.runPromise(program);

Read the full file on GitHub · 157 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 7d ago First seen · 157 lines · 1,020 tokens per session scan A d112bb19ca99

Subscribe to this mod's changes

concurrency-pattern-2-rate-limit-concurrent-access-with-semaphore is a cursor rule published in the GitHub repository PaulJPhilp/EffectPatterns (796 stars, last pushed 2mo ago), licensed MIT. It adds 1,020 tokens to every session, about $0.0051 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.