Community코딩 & 개발github.com

cognitedata/dm-limits-and-best-practices

CDF 데이터 모델링 API 모범 사례를 위한 참조 스킬입니다. 동시성 제한(429 오류 방지), 인스턴스 목록 조회 및 쿼리 페이지네이션 패턴, 쓰기 작업 배치, 검색 vs 필터 가이드, 그리고 동시 요청을 제어하기 위한 QueuedTaskRunner(세마포어) 유틸리티를 다룹니다.

dm-limits-and-best-practices란 무엇인가요?

이 스킬은 CDF(Cognite Data Fusion) Data Modeling API를 사용하는 개발자를 위한 모범 사례 가이드입니다. 주요 기능으로는 API 호출 시 429(Too Many Requests) 오류를 피하기 위한 동시성 제한 처리, `instances.list` 및 `instances.query` 엔드포인트에서 효율적인 페이지네이션(커서 기반 반복) 패턴 제공, 대량 쓰기 작업을 위한 배치 전략, `instances.search` vs `instances.filter` 사용 시기 안내, 그리고 `QueuedTaskRunner`(일명 `cdfTaskRunner` 또는 세마포어)를 활용한 동시 요청 수 제어 방법을 포함합니다. 이 스킬은 Claude Code, Cursor, Codex와 같은 AI 에이전트 플랫폼에서 사용할 수 있으며, DMS(Data Modeling Service) 한도, 429 오류, 속도 제한, 페이지네이션, 배치 처리, 데드락과 같은 트리거에 반응하여 개발자가 안정적이고 효율적인 CDF 애플리케이션을 구축하도록 돕습니다.

지원 대상~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/cognitedata/builder-skills/tree/main/skills/dm-limits-and-best-practices

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

dm-limits-and-best-practices은(는) 무엇을 하나요?

CDF Data Modeling API 모범 사례를 위한 참조 스킬입니다. 동시성 제한(429 오류 방지), instances.list 및 instances.query에 대한 페이지네이션 패턴, 쓰기 작업 배치, 검색 vs 필터 가이드, 그리고 동시 요청을 제어하기 위한 QueuedTaskRunner(세마포어) 유틸리티를 다룹니다.

트리거: DMS 제한, 429 오류, 속도 제한(rate limit), 페이지네이션(pagination), 커서(cursor), nextCursor, 배치(batching), 세마포어(semaphore), QueuedTaskRunner, cdfTaskRunner, instances.search, instances.list, instances.query, instances.upsert, 동시성(concurrency), 데드락(deadlock).

동시성 제한 및 429 오류 방지

CDF API에는 호출당 허용되는 최대 동시 요청 수가 있습니다. 이 제한을 초과하면 429 Too Many Requests 응답이 반환됩니다.

  • 기본 동시성 제한: API 엔드포인트당 10개의 동시 요청입니다.
  • 429 응답 처리: 429 오류가 발생하면 지수 백오프(Exponential Backoff)와 재시도 로직을 구현해야 합니다.
  • 권장사항: QueuedTaskRunner(아래 참조)를 사용하여 동시 요청을 제한함으로써 429 오류를 사전에 방지하세요.

페이지네이션 패턴

instances.list

instances.list는 결과를 페이지 단위로 반환합니다. 각 응답에는 다음 페이지를 가져오는 데 사용할 수 있는 nextCursor 필드가 포함됩니다.

# 예시: instances.list 페이지네이션
cursor = None
while True:
    response = client.data_modeling.instances.list(
        space="my_space",
        limit=1000,
        cursor=cursor
    )
    # 결과 처리
    for instance in response.instances:
        process(instance)
    
    cursor = response.nextCursor
    if cursor is None:
        break

instances.query

instances.query도 페이지네이션을 지원합니다. 쿼리 결과가 큰 경우 nextCursor를 사용하여 모든 결과를 반복하세요.

# 예시: instances.query 페이지네이션
query = {
    "with": {
        "items": {
            "nodes": {
                "filter": {
                    "equals": {
                        "property": ["node", "type"],
                        "value": {"space": "my_space", "externalId": "MyType"}
                    }
                },
                "limit": 100
            }
        }
    },
    "select": {
        "items": []
    }
}

cursor = None
while True:
    if cursor:
        query["cursor"] = cursor
    response = client.data_modeling.instances.query(query)
    # 결과 처리
    for item in response.items:
        process(item)
    
    cursor = response.nextCursor
    if cursor is None:
        break

쓰기 작업 배치

대량의 인스턴스를 생성하거나 업데이트할 때는 단일 요청으로 처리하는 것보다 배치로 나누는 것이 좋습니다.

  • 배치 크기 권장: 요청당 최대 1000개의 인스턴스
  • 동시 배치: QueuedTaskRunner를 사용하여 여러 배치를 동시에 전송하되, 전체 동시성 제한을 초과하지 않도록 하세요.
from cognite.client.data_classes import InstanceWrite

def batch_upsert_instances(client, instances: list[InstanceWrite], batch_size=1000, max_concurrency=5):
    """인스턴스를 배치로 upsert하고 동시성을 제어합니다."""
    from cognite.client.utils import QueuedTaskRunner
    
    runner = QueuedTaskRunner(max_concurrency=max_concurrency)
    
    for i in range(0, len(instances), batch_size):
        batch = instances[i:i + batch_size]
        runner.submit(client.data_modeling.instances.upsert, batch)
    
    runner.wait_for_completion()

검색 vs 필터 가이드

  • instances.search: 텍스트 검색 및 퍼지 매칭(fuzzy matching)에 사용합니다. 특정 속성 값에 대한 전체 텍스트 검색이 필요할 때 적합합니다.
  • instances.filter: 속성 값에 대한 정확한 일치, 범위 쿼리, 존재 여부 확인 등 구조화된 필터링에 사용합니다. 검색보다 성능이 뛰어나며 대규모 데이터셋에 권장됩니다.

일반 규칙: 가능하면 항상 filter를 사용하고, 텍스트 기반 검색이 정말 필요할 때만 search를 사용하세요.

QueuedTaskRunner (세마포어) 유틸리티

QueuedTaskRunner는 동시 실행되는 태스크 수를 제한하는 유틸리티입니다. cdfTaskRunner로도 알려져 있습니다.

주요 특징

  • 동시 요청 수를 사용자 정의 가능한 한도로 제한합니다.
  • 완료될 때까지 태스크를 자동으로 큐에 대기시킵니다.
  • 예외를 포착하고 보고합니다.

사용 예시

from cognite.client.utils import QueuedTaskRunner

# 최대 5개의 동시 요청으로 러너 생성
runner = QueuedTaskRunner(max_concurrency=5)

# 태스크 제출 (즉시 실행되지 않고 큐에 추가됨)
for item in items:
    runner.submit(process_item, item)

# 모든 태스크가 완료될 때까지 대기
runner.wait_for_completion()

# 예외 확인
if runner.exceptions:
    for exc in runner.exceptions:
        print(f"태스크 실패: {exc}")

전체 예시: 안전한 대량 Upsert

다음은 모든 모범 사례를 결합한 종합 예시입니다.

from cognite.client import CogniteClient
from cognite.client.data_classes import InstanceWrite
from cognite.client.utils import QueuedTaskRunner

client = CogniteClient()

# 업서트할 인스턴스 목록 (예시)
instances = [...]  # 많은 인스턴스

BATCH_SIZE = 500
MAX_CONCURRENCY = 5

def upsert_batch(batch):
    """단일 배치를 upsert하고 결과를 반환합니다."""
    return client.data_modeling.instances.upsert(batch)

runner = QueuedTaskRunner(max_concurrency=MAX_CONCURRENCY)

# 인스턴스를 배치로 나누고 태스크 제출
for i in range(0, len(instances), BATCH_SIZE):
    batch = instances[i:i + BATCH_SIZE]
    runner.submit(upsert_batch, batch)

# 완료 대기
runner.wait_for_completion()

# 오류 처리
if runner.exceptions:
    print(f"다음 개수의 배치가 실패했습니다: {len(runner.exceptions)}")
    for exc in runner.exceptions:
        print(f"  오류: {exc}")
else:
    print(f"모든 {len(instances)}개 인스턴스가 성공적으로 upsert되었습니다.")

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

cognitedata/code-quality

MUST be used whenever reviewing a Flows app for code quality, maintainability, or clean code issues — before a PR review, after a feature is complete, or when the user asks for a code review. Do NOT skip linting steps. Triggers: code quality, code review, clean code, refactor, maintainability, technical debt, any type, naming, dead code, duplication, DRY, single responsibility, component size, lint, linting, TypeScript strict, dependency injection, file structure.

cognitedata/correctness-and-error-handling

MUST be used whenever fixing correctness and error handling issues in a Flows app. This skill finds AND fixes bugs, missing error states, unhandled rejections, and edge-case failures — it does not just report them. Triggers: correctness, error handling, bug fix, edge case, crash, unhandled, null, undefined, empty state, loading state, error boundary, try catch, async error, useEffect cleanup, type guard, runtime error, robustness.

cognitedata/create-client-tool

MUST be used whenever creating an AtlasTool (client-side tool) for an Atlas agent. Do NOT manually write AtlasTool definitions or wire them into useAtlasChat — this skill handles the TypeBox schema, execute function, and hook wiring. Prerequisite: integrate-atlas-chat (vendored src/atlas-agent + TypeBox/AJV deps). This includes tools that fetch data, render UI, call APIs, show charts, query local state, or perform any browser-side action. Triggers: AtlasTool, client tool, add tool, create tool, new tool, tool definition, agent tool.

cognitedata/dependencies-audit

MUST be used whenever fixing dependency issues in a Flows app. This skill finds AND fixes vulnerabilities, outdated packages, deprecated dependencies, and license issues — it does not just report them. Triggers: dependencies, packages, fix dependencies, update packages, fix vulnerabilities, npm audit fix, pnpm audit fix, CVE fix, outdated, deprecated, supply chain, license.

cognitedata/design

Simplified Aura guidance for selecting primitives, keeping token usage consistent, and applying reliable layout/copy/state patterns in Flows and Fusion apps.

cognitedata/flows-code-review

Run the technical (code) review step of Flows app certification. Produces three artifacts under reviews/code-review/feedback-round-<N>/: review-files.md (per-file inventory), review-packages.md (dependency audit), and code-review-report.md (scored report with Must Fix / Should Fix / Nice Fix items). Use when the user asks for a Flows code review, technical review, pre-submit review, app certification code review, or "run flows-code-review". Re-run until 0 open Must Fix items remain before moving on to flows-design-review.

cognitedata/graph-viewer

Integrate the reusable CDF graph viewer (useGraphViewer) into a Flows app by copying the local code bundle. Use when embedding a graph visualization, adding a knowledge graph, or showing CDF data model relationships and instances.

cognitedata/integrate-atlas-chat

MUST be used whenever building a chat UI with Atlas agents in a Flows app. Do NOT manually write useAtlasChat integration code — this skill handles installation, component structure, and hook wiring. Triggers: useAtlasChat, atlas chat, streaming chat, agent chat, chat interface, chat component, chat UI. For a full chat app, run skills in order: (1) integrate-atlas-chat, (2) create-client-tool (per tool), (3) setup-python-tools (if Python tools needed).

cognitedata/integrate-file-viewer

MUST be used whenever integrating CogniteFileViewer into a Flows app to preview CDF files (PDFs, images, text). Do NOT manually wire up react-pdf or file resolution — this skill handles installation, Vite config, worker setup, and component usage. Triggers: file viewer, file preview, CogniteFileViewer, PDF viewer, view CDF files, document viewer, preview file.

cognitedata/integrate-fusion-agent

Integrates a Flows/Dune app with the Fusion built-in PAIA agent panel using @cognite/app-sdk. Use this skill whenever a developer wants to: open the agent panel from their app, send the agent a contextual message, let the agent read app state (resources), or let the agent call actions in the app. Triggers: "fusion agent", "PAIA", "agent panel", "sendAgentMessage", "sendAgentLayoutMode", "agent server", "registerAgentServer", "connectToHostApp", "agent integration", "agent sidebar", "app-sdk agent". Always use this skill instead of manually writing agent integration code — it sets up the correct lifecycle, graceful fallback, and recommended file structure.

cognitedata/integrate-todo-list

MUST be used whenever adding a task/todo list feature to a Flows app with Atlas chat. Do NOT manually create todo state management or tool definitions — this skill handles the full module (context, provider, tool, hooks, UI components) and all integration wiring. Prerequisite: integrate-atlas-chat must already be set up. Triggers: todo list, task list, task tracking, TodoWrite, todo panel, task panel, progress tracking, add todos, add tasks.

cognitedata/migrate-app-to-flows

MUST be used when migrating a legacy Dune app to the new Flows app hosting infrastructure. Orchestrates the full migration: audits current state, updates app.json to appsApi infra, delegates auth wiring to setup-flows-auth, creates or updates manifest.json network permissions, and updates deploy scripts to @cognite/cli. Use this whenever a user says 'migrate to Flows', 'migrate to new infra', 'move from dune to flows', 'migrate legacy app', or wants to move their existing app to the new Flows app hosting.

cognitedata/performance

MUST be used whenever fixing performance issues in a Flows app. This skill finds AND fixes performance problems — re-renders, inefficient queries, missing pagination, unbounded fetches, large bundles, and memory leaks. It does not just report them. Always measure before and after. Triggers: performance, slow, laggy, optimize, re-render, bundle size, load time, CDF query, large list, memory leak, debounce, virtualize, lazy load, code split.

cognitedata/pull-changes-resolve-conflicts

Standard workflow for pulling updates from main or other branches on multi-contributor projects (including Flows apps) without silently discarding work. Guides fetching/merging, requires listing merge conflicts explicitly, analyzing ours vs theirs using conversation history and repo context, presenting prioritized recommendations, and obtaining user answers before editing conflict markers or completing the merge. Triggers: pull main, merge main, merge origin, rebase, merge conflict, unmerged paths, both modified, integrate branch, sync with main, git merge abort, resolve conflicts, UU status, theirs vs ours, feat branch update.

cognitedata/reveal-3d

Integrates a local Cognite Reveal 3D CAD viewer bundle into Flows apps by copying app-local source code. Use when adding 3D viewer, 3D visualization, Reveal, CAD model, RevealProvider, RevealCanvas, Reveal3DResources, FDM 3D mapping, asset 3D model, model browser, or Cognite 3D content to a Flows application.

cognitedata/security

MUST be used whenever fixing security issues in a Flows app, or before shipping any feature that handles credentials, user input, or external data. This skill finds AND fixes security problems — it does not just report them. Do NOT skip this when the user asks for a security fix, security hardening, or vulnerability remediation — run every step in order. Triggers: security, security fix, security hardening, vulnerability, XSS, injection, credentials, secrets, auth, authentication, authorization, token, sensitive data, input validation, CORS, CSP, dependency audit.

cognitedata/setup-flows-auth

MUST be used when migrating an existing React app to Flows, or when no Flows auth is wired up. Detects classic vs Apps API flow from `app.json` `infra` field, installs the right packages, and wires up the entry file. No-op when a valid auth setup is already in place. Triggers: migrate to Flows, add Flows auth, DuneAuthProvider, AppSdkAuthProvider, connectToHostApp, useDune, Flows setup, setup auth, missing auth provider, CDF authentication, Fusion iframe auth.

cognitedata/setup-python-tools

MUST be used when adding Pyodide or Python tool support to a Flows app. Do NOT manually configure usePyodideRuntime or wire pythonRuntime into useAtlasChat — this skill handles pyodide installation, hook setup, loading UI, and chat hook wiring. Prerequisite: integrate-atlas-chat (vendored src/atlas-agent + atlas chat wiring). Triggers: Pyodide, Python tools, pythonRuntime, usePyodideRuntime, runPythonCode, Python execution, client-side Python.

cognitedata/skill-creator

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch for Claude Code or Cursor, update or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

cognitedata/test-coverage

MUST be used whenever fixing test coverage for a Flows app to meet the 80% line coverage hard gate. This skill finds AND fixes coverage gaps — it configures tooling, writes missing tests, covers untested paths, and refactors code for testability. It does not just report. Triggers: test coverage, fix tests, write tests, add tests, coverage fix, 80% coverage, coverage gate, missing tests, testability, vitest coverage, jest coverage.

관련 스킬