Optimisation des performances Juicebox

VérifiéPrudence

Optimisez l'intégration API Juicebox pour réduire la latence et améliorer les temps de réponse. Implémentez la mise en cache, le traitement par lot et l'optimisation des requêtes.

Spar Skills Guide Bot
DeveloppementIntermédiaire
08/03/2026
Claude Code
#api-performance#caching#request-batching#latency-optimization#typescript

Recommandé pour

Synthèse automatique

Ce skill guide l’optimisation des intégrations à l’API Juicebox via du cache Redis, le regroupement de requêtes et le pooling de connexions.

Points forts

  • Fournit des exemples TypeScript concrets pour un cache Redis avec TTL et invalidation.
  • Propose un processeur de lots configurable (taille maximale et délai d’attente) pour réduire les appels API.
  • Structure la démarche en étapes : cache, batching et pooling de connexions.
  • Rappelle les prérequis de mesure : intégration fonctionnelle, monitoring et métriques de référence.

Limites

  • Le contenu fourni s’arrête au milieu de l’exemple de pooling de connexions ; cette partie n’est pas exploitable en l’état.
  • Suppose une stack TypeScript/Node.js avec Redis et le SDK Juicebox, sans alternative pour d’autres langages.
  • Ne détaille pas la validation des gains, les règles d’invalidation métier ni la gestion des erreurs de cache.
Quand l'utiliser

À utiliser lorsqu’une intégration Juicebox existante est déjà mesurée et que l’on veut réduire la latence ou la charge API.

Quand l'éviter

À éviter si l’intégration Juicebox n’est pas encore fonctionnelle ou si l’on cherche des optimisations indépendantes de Redis et du SDK Node.js.

Analyse de sécurité

Prudence
Score qualité74/100

The skill provides performance-tuning code examples and does not contain destructive, exfiltration, obfuscated, or safety-disabling instructions. The only notable risk is the broad declared Bash access via curl and gh, which is network-capable even though it is not exercised in the instructions.

Points d'attention
  • •Declared Bash(curl:*) permission is broader than what the skill actually demonstrates (no curl/network commands appear in the instructions), granting unnecessary execution capability.
  • •Code reads credentials from environment variables (process.env.JUICEBOX_API_KEY, REDIS_URL), which is the correct pattern; no secret handling is exposed.
  • •Declared allowed tools include Bash(curl:*) and Bash(gh:*), which permit network and GitHub CLI access; the skill content does not use these tools, but they are powerful capabilities.
Comment cette analyse est faite

Exemples

Add Redis caching
Add Redis caching to our Juicebox people search endpoint with a 5-minute TTL and measure the latency improvement.
Batch profile enrichment
Implement request batching for Juicebox profile enrichment with a maximum batch size of 50 and a 100 ms max wait.
Tune Juicebox latency
Help me tune Juicebox API latency; our integration works and we already have monitoring and baseline metrics.

name: juicebox-performance-tuning description: | Optimize Juicebox API performance. Use when improving response times, reducing latency, or optimizing Juicebox integration throughput. Trigger with phrases like "juicebox performance", "optimize juicebox", "juicebox speed", "juicebox latency". allowed-tools: Read, Write, Edit, Bash(gh:), Bash(curl:) version: 1.0.0 license: MIT author: Jeremy Longshore jeremy@intentsolutions.io

Juicebox Performance Tuning

Overview

Optimize Juicebox API integration for maximum performance and minimal latency.

Prerequisites

  • Working Juicebox integration
  • Performance monitoring in place
  • Baseline metrics established

Instructions

Step 1: Implement Response Caching

// lib/juicebox-cache.ts
import { Redis } from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

interface CacheOptions {
  ttl: number; // seconds
  prefix?: string;
}

export class JuiceboxCache {
  constructor(private options: CacheOptions = { ttl: 300 }) {}

  private getKey(type: string, params: any): string {
    const hash = crypto
      .createHash('md5')
      .update(JSON.stringify(params))
      .digest('hex');
    return `${this.options.prefix || 'jb'}:${type}:${hash}`;
  }

  async get<T>(type: string, params: any): Promise<T | null> {
    const key = this.getKey(type, params);
    const cached = await redis.get(key);
    return cached ? JSON.parse(cached) : null;
  }

  async set<T>(type: string, params: any, data: T): Promise<void> {
    const key = this.getKey(type, params);
    await redis.setex(key, this.options.ttl, JSON.stringify(data));
  }

  async invalidate(type: string, params: any): Promise<void> {
    const key = this.getKey(type, params);
    await redis.del(key);
  }
}

// Usage
const cache = new JuiceboxCache({ ttl: 300 });

async function searchWithCache(query: string, options: SearchOptions) {
  const cached = await cache.get('search', { query, ...options });
  if (cached) return cached;

  const results = await client.search.people({ query, ...options });
  await cache.set('search', { query, ...options }, results);
  return results;
}

Step 2: Optimize Request Batching

// lib/batch-processor.ts
export class BatchProcessor<T, R> {
  private queue: Array<{
    item: T;
    resolve: (result: R) => void;
    reject: (error: Error) => void;
  }> = [];
  private timeout: NodeJS.Timeout | null = null;

  constructor(
    private processBatch: (items: T[]) => Promise<R[]>,
    private options: { maxSize: number; maxWait: number }
  ) {}

  async add(item: T): Promise<R> {
    return new Promise((resolve, reject) => {
      this.queue.push({ item, resolve, reject });

      if (this.queue.length >= this.options.maxSize) {
        this.flush();
      } else if (!this.timeout) {
        this.timeout = setTimeout(() => this.flush(), this.options.maxWait);
      }
    });
  }

  private async flush(): Promise<void> {
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }

    if (this.queue.length === 0) return;

    const batch = this.queue.splice(0, this.options.maxSize);
    const items = batch.map(b => b.item);

    try {
      const results = await this.processBatch(items);
      batch.forEach((b, i) => b.resolve(results[i]));
    } catch (error) {
      batch.forEach(b => b.reject(error as Error));
    }
  }
}

// Usage for profile enrichment
const enrichmentBatcher = new BatchProcessor<string, Profile>(
  async (profileIds) => {
    return client.profiles.batchGet(profileIds);
  },
  { maxSize: 50, maxWait: 100 }
);

// Automatic batching
const profile = await enrichmentBatcher.add(profileId);

Step 3: Connection Pooling

// lib/connection-pool.ts
import { JuiceboxClient } from '@juicebox/sdk';

class ClientPool {
  private clients: JuiceboxClient[] = [];
  private currentIndex = 0;

  constructor(size: number, apiKey: string) {
    for (let i = 0; i < size; i++) {
      this.clients.push(new JuiceboxClient({
        apiKey,
        keepAlive: true,
        timeout: 30000
      }));
    }
  }

  getClient(): JuiceboxClient {
    const client = this.clients[this.currentIndex];
    this.currentIndex = (this.currentIndex + 1) % this.clients.length;
    return client;
  }
}

const pool = new ClientPool(5, process.env.JUICEBOX_API_KEY!);

Step 4: Query Optimization

// lib/query-optimizer.ts
export function optimizeSearchQuery(params: SearchParams): SearchParams {
  return {
    ...params,
    // Only request needed fields
    fields: params.fields || ['id', 'name', 'title', 'company'],
    // Use reasonable page size
    limit: Math.min(params.limit || 20, 100),
    // Disable expensive features if not needed
    includeScores: params.includeScores ?? false,
    includeHighlights: params.includeHighlights ?? false
  };
}

// Pagination optimization
async function* streamResults(query: string) {
  let cursor: string | undefined;

  do {
    const results = await client.search.people({
      query,
      limit: 100,
      cursor,
      fields: ['id', 'name', 'title'] // Minimal fields for listing
    });

    for (const profile of results.profiles) {
      yield profile;
    }

    cursor = results.nextCursor;
  } while (cursor);
}

Step 5: Monitor Performance

// lib/performance-monitor.ts
import { metrics } from './metrics';

export function wrapWithMetrics<T extends (...args: any[]) => Promise<any>>(
  name: string,
  fn: T
): T {
  return (async (...args: Parameters<T>) => {
    const start = Date.now();
    try {
      const result = await fn(...args);
      metrics.histogram(`juicebox.${name}.duration`, Date.now() - start);
      metrics.increment(`juicebox.${name}.success`);
      return result;
    } catch (error) {
      metrics.increment(`juicebox.${name}.error`);
      throw error;
    }
  }) as T;
}

// Dashboard query
const performanceQuery = `
  SELECT
    date_trunc('hour', timestamp) as hour,
    avg(duration_ms) as avg_latency,
    percentile_cont(0.95) within group (order by duration_ms) as p95,
    count(*) as requests
  FROM juicebox_metrics
  WHERE timestamp > now() - interval '24 hours'
  GROUP BY 1
  ORDER BY 1
`;

Performance Benchmarks

| Operation | Target | Optimization | |-----------|--------|--------------| | Search (cold) | < 500ms | Query optimization | | Search (cached) | < 50ms | Redis cache | | Profile fetch | < 200ms | Batch requests | | Bulk enrichment | < 2s/100 | Connection pool |

Output

  • Response caching layer
  • Request batching system
  • Connection pool
  • Performance monitoring

Resources

Next Steps

After performance tuning, see juicebox-cost-tuning for cost optimization.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/juicebox-performance-tuning-mmh8qqrx' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/juicebox-performance-tuning-mmh8qqrx/download' --output '.skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md.part' && mv '.skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md.part' '.skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Edit, Bash(gh:*), Bash(curl:*)

Extrait original : Prerequisites
  • Working Juicebox integration
  • Performance monitoring in place
  • Baseline metrics established

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md' && test -s '.skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/juicebox-performance-tuning' && cp -R '.skill-downloads/juicebox-performance-tuning-mmh8qqrx' '.claude/skills/juicebox-performance-tuning'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/juicebox-performance-tuning-mmh8qqrx'

openskills read 'juicebox-performance-tuning-mmh8qqrx'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/juicebox-performance-tuning-mmh8qqrx/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires