CommunityProgramación y desarrollogithub.com

cognitedata/dm-limits-and-best-practices

Habilidad de referencia para las mejores prácticas de la API de Data Modeling de CDF. Cubre límites de concurrencia (evitando errores 429), patrones de paginación para operaciones de instancias.list y instancias.query, operaciones de escritura por lotes, guía de búsqueda vs filtro y la utilidad QueuedTaskRunner (Semáforo) para controlar solicitudes concurrentes.

¿Qué es dm-limits-and-best-practices?

Esta habilidad te guía a través de las mejores prácticas para trabajar con la API de Data Modeling (DMS) de CDF. Está diseñada para ayudarte a evitar errores de límite de velocidad (429), manejar la paginación de manera eficiente con `instancias.list` e `instancias.query`, y optimizar las operaciones de escritura mediante el procesamiento por lotes. También proporciona orientación sobre cuándo usar `instancias.search` en lugar de `instancias.filter`, y presenta `QueuedTaskRunner` (Semáforo) como una utilidad para controlar la concurrencia y prevenir condiciones de bloqueo. Esta habilidad es útil para cualquier desarrollador o agente de IA que interactúe con CDF DMS y busque construir aplicaciones robustas, eficientes y resistentes a errores. Soporta plataformas como Claude Code y Cursor, y su documentación detalla implementaciones prácticas en Python y TypeScript.

Compatible con~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 Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

¿Qué hace dm-limits-and-best-practices?

Habilidad de referencia para las mejores prácticas de la API de Data Modeling de CDF. Cubre límites de concurrencia (evitando errores 429), patrones de paginación para instances.list e instances.query, operaciones de escritura por lotes, guía de búsqueda vs filtro y la utilidad QueuedTaskRunner (Semáforo) para controlar solicitudes concurrentes. Desencadenantes: Límites de DMS, error 429, límite de velocidad, paginación, cursor, nextCursor, procesamiento por lotes, semáforo, QueuedTaskRunner, cdfTaskRunner, instances.search, instances.list, instances.query, instances.upsert, concurrencia, bloqueo.

Introducción

Al trabajar con la API de Data Modeling (DMS) de CDF, es importante seguir las mejores prácticas para garantizar un rendimiento y una fiabilidad óptimos. Esta habilidad proporciona orientación sobre cómo manejar la concurrencia, la paginación, el procesamiento por lotes y otras operaciones comunes.

Límites de concurrencia y errores 429

La API de DMS tiene límites de concurrencia para proteger el sistema de ser sobrecargado. Cuando se excede un límite, la API devuelve un error HTTP 429 (Demasiadas solicitudes). Para evitar esto:

  • Utiliza la utilidad QueuedTaskRunner (Semáforo) para controlar el número de solicitudes concurrentes.
  • Implementa retroceso exponencial y reintentos para manejar errores 429.
  • Monitorea los límites de velocidad actuales a través de los encabezados de respuesta.

Ejemplo en Python:

from cognite.client import CogniteClient
from cognite.client.data_classes import InstanceList

client = CogniteClient()

# Crear un QueuedTaskRunner con un máximo de 5 tareas concurrentes
runner = client.iam.queued_task_runner(max_concurrent=5)

def fetch_instances(space, external_id):
    return client.data_modeling.instances.list(space=space, external_id=[external_id])

# Encolar tareas y ejecutarlas concurrentemente
task1 = runner.submit(fetch_instances, "space1", "id1")
task2 = runner.submit(fetch_instances, "space1", "id2")
result1 = task1.result()
result2 = task2.result()

Paginación

instances.list

Al listar instancias, la API devuelve resultados paginados. Utiliza el cursor para recorrer todas las páginas:

from cognite.client import CogniteClient

client = CogniteClient()
cursor = None
all_instances = []

while True:
    result = client.data_modeling.instances.list(space="mi_espacio", cursor=cursor, limit=1000)
    all_instances.extend(result.data)
    if result.cursor is None:
        break
    cursor = result.cursor

instances.query

Para consultas que devuelven muchas instancias, utiliza la paginación con nextCursor:

cursor = None
while True:
    result = client.data_modeling.instances.query(
        filter=...,
        cursor=cursor,
        limit=1000
    )
    # Procesar resultados
    if result.next_cursor is None:
        break
    cursor = result.next_cursor

Operaciones de escritura por lotes

Al crear o actualizar instancias, agrupa las operaciones en lotes para reducir la cantidad de solicitudes:

from cognite.client.data_classes import InstanceWrite

lote = []
for i in range(1000):
    lote.append(InstanceWrite(space="mi_espacio", external_id=f"id_{i}", ...))
    if len(lote) == 100:
        client.data_modeling.instances.upsert(lote)
        lote = []
# Enviar el lote restante
if lote:
    client.data_modeling.instances.upsert(lote)

Búsqueda vs Filtro

  • instances.search: Úsalo cuando necesites buscar por términos de texto en campos indexados para búsqueda. Es útil para búsquedas por palabras clave.
  • instances.filter: Úsalo para filtrar por propiedades exactas, rangos o condiciones booleanas. Es más eficiente para consultas estructuradas.
OperaciónCaso de usoRendimiento
instances.searchBúsqueda por texto flexiblePuede ser más lento en conjuntos de datos grandes
instances.filterFiltros exactos y estructuradosGeneralmente más rápido

QueuedTaskRunner (Semáforo)

QueuedTaskRunner es una utilidad que te permite controlar la concurrencia de las solicitudes a la API de CDF. Funciona como un semáforo, limitando el número de tareas que se ejecutan simultáneamente.

Beneficios:

  • Previene la sobrecarga del sistema y errores 429.
  • Mejora la fiabilidad de las aplicaciones.
  • Simplifica el código de control de concurrencia.

Ejemplo en TypeScript:

import { CogniteClient } from "@cognite/sdk";

const client = new CogniteClient({ appId: "mi-app", project: "mi-proyecto" });

const runner = client.createQueuedTaskRunner({ maxConcurrent: 5 });

async function fetchInstance(space: string, externalId: string) {
    return client.dataModeling.instances.list({ space, externalId: [externalId] });
}

const tasks = [
    runner.submit(() => fetchInstance("space1", "id1")),
    runner.submit(() => fetchInstance("space1", "id2")),
];

const results = await Promise.all(tasks);

Resumen de desencadenadores

  • DMS limits: Errores relacionados con límites de la API de Data Modeling.
  • 429 error: Error de límite de velocidad.
  • Rate limit: Límite de velocidad genérico.
  • Pagination: Necesidad de recorrer páginas de resultados.
  • Cursor / nextCursor: Parámetros para la paginación.
  • Batching: Agrupación de operaciones para eficiencia.
  • Semaphore / QueuedTaskRunner / cdfTaskRunner: Herramientas para control de concurrencia.
  • instances.search / instances.list / instances.query / instances.upsert: Operaciones específicas de la API.
  • Concurrency / deadlock: Problemas de concurrencia y bloqueos.

Referencias adicionales

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.

Skills relacionados