Network
Deploy Algolia integrations to Vercel, Fly.
ReadWriteEditBash(vercel:*)Bash(fly:*)Bash(gcloud:*)
Algolia Deploy Integration
Overview
Deploy Algolia-powered applications to popular platforms with proper secrets management.
Prerequisites
- Algolia API keys for production environment
- Platform CLI installed (vercel, fly, or gcloud)
- Application code ready for deployment
- Environment variables documented
Vercel Deployment
Environment Setup
# Add Algolia secrets to Vercel
vercel secrets add algolia_api_key sk_live_***
vercel secrets add algolia_webhook_secret whsec_***
# Link to project
vercel link
# Deploy preview
vercel
# Deploy production
vercel --prod
vercel.json Configuration
{
"env": {
"ALGOLIA_API_KEY": "@algolia_api_key"
},
"functions": {
"api/**/*.ts": {
"maxDuration": 30
}
}
}
Fly.io Deployment
fly.toml
app = "my-algolia-app"
primary_region = "iad"
[env]
NODE_ENV = "production"
[http_service]
internal_port = 3000
force_https = true
auto_stop_machines = true
auto_start_machines = true
Secrets
# Set Algolia secrets
fly secrets set ALGOLIA_API_KEY=sk_live_***
fly secrets set ALGOLIA_WEBHOOK_SECRET=whsec_***
# Deploy
fly deploy
Google Cloud Run
Dockerfile
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
CMD ["npm", "start"]
Deploy Script
#!/bin/bash
# deploy-cloud-run.sh
PROJECT_ID="${GOOGLE_CLOUD_PROJECT}"
SERVICE_NAME="algolia-service"
REGION="us-central1"
# Build and push image
gcloud builds submit --tag gcr.io/$PROJECT_ID/$SERVICE_NAME
# Deploy to Cloud Run
gcloud run deploy $SERVICE_NAME \
--image gcr.io/$PROJECT_ID/$SERVICE_NAME \
--region $REGION \
--platform managed \
--allow-unauthenticated \
--set-secrets=ALGOLIA_API_KEY=algolia-api-key:latest
Environment Configuration Pattern
// config/algolia.ts
interface AlgoliaConfig {
apiKey: string;
environment: 'development' | 'staging' | 'production';
webhookSecret?: string;
}
export function getAlgoliaConfig(): AlgoliaConfig {
const env = process.env.NODE_ENV || 'development';
return {
apiKey: process.env.ALGOLIA_API_KEY!,
environment: env as AlgoliaConfig['environment'],
webhookSecret: process.env.ALGOLIA_WEBHOOK_SECRET,
};
}
Health Check Endpoint
// api/health.ts
export async function GET() {
const algoliaStatus = await checkAlgoliaConnection();
return Response.json({
Configure Algolia enterprise SSO, role-based access control, and organization management.
ReadWriteEdit
Algolia Enterprise RBAC
Overview
Configure enterprise-grade access control for Algolia integrations.
Prerequisites
- Algolia Enterprise tier subscription
- Identity Provider (IdP) with SAML/OIDC support
- Understanding of role-based access patterns
- Audit logging infrastructure
Role Definitions
| Role |
Permissions |
Use Case |
| Admin |
Full access |
Platform administrators |
| Developer |
Read/write, no delete |
Active development |
| Viewer |
Read-only |
Stakeholders, auditors |
| Service |
API access only |
Automated systems |
Role Implementation
enum AlgoliaRole {
Admin = 'admin',
Developer = 'developer',
Viewer = 'viewer',
Service = 'service',
}
interface AlgoliaPermissions {
read: boolean;
write: boolean;
delete: boolean;
admin: boolean;
}
const ROLE_PERMISSIONS: Record<AlgoliaRole, AlgoliaPermissions> = {
admin: { read: true, write: true, delete: true, admin: true },
developer: { read: true, write: true, delete: false, admin: false },
viewer: { read: true, write: false, delete: false, admin: false },
service: { read: true, write: true, delete: false, admin: false },
};
function checkPermission(
role: AlgoliaRole,
action: keyof AlgoliaPermissions
): boolean {
return ROLE_PERMISSIONS[role][action];
}
SSO Integration
SAML Configuration
// Algolia SAML setup
const samlConfig = {
entryPoint: 'https://idp.company.com/saml/sso',
issuer: 'https://algolia.com/saml/metadata',
cert: process.env.SAML_CERT,
callbackUrl: 'https://app.yourcompany.com/auth/algolia/callback',
};
// Map IdP groups to Algolia roles
const groupRoleMapping: Record<string, AlgoliaRole> = {
'Engineering': AlgoliaRole.Developer,
'Platform-Admins': AlgoliaRole.Admin,
'Data-Team': AlgoliaRole.Viewer,
};
OAuth2/OIDC Integration
import { OAuth2Client } from '@algolia/sdk';
const oauthClient = new OAuth2Client({
clientId: process.env.ALGOLIA_OAUTH_CLIENT_ID!,
clientSecret: process.env.ALGOLIA_OAUTH_CLIENT_SECRET!,
redirectUri: 'https://app.yourcompany.com/auth/algolia/callback',
scopes: ['read', 'write'],
});
Organization Management
interface AlgoliaOrganization {
id: string;
name: string;
ssoEnabled: boolean;
enforceSso: boolean;
allowedDomains: string[];
defaultRole: AlgoliaRole;
}
async function createOrganization(
config: AlgoliaOrganization
): Promise<void> {
await algoliaClient.org
Create a minimal working Algolia example.
ReadWriteEdit
Algolia Hello World
Overview
Minimal working example demonstrating core Algolia functionality.
Prerequisites
- Completed
algolia-install-auth setup
- Valid API credentials configured
- Development environment ready
Instructions
Step 1: Create Entry File
Create a new file for your hello world example.
Step 2: Import and Initialize Client
import { AlgoliaClient } from '@algolia/sdk';
const client = new AlgoliaClient({
apiKey: process.env.ALGOLIA_API_KEY,
});
Step 3: Make Your First API Call
async function main() {
// Your first API call here
}
main().catch(console.error);
Output
- Working code file with Algolia client initialization
- Successful API response confirming connection
- Console output showing:
Success! Your Algolia connection is working.
Error Handling
| Error |
Cause |
Solution |
| Import Error |
SDK not installed |
Verify with npm list or pip show |
| Auth Error |
Invalid credentials |
Check environment variable is set |
| Timeout |
Network issues |
Increase timeout or check connectivity |
| Rate Limit |
Too many requests |
Wait and retry with exponential backoff |
Examples
TypeScript Example
import { AlgoliaClient } from '@algolia/sdk';
const client = new AlgoliaClient({
apiKey: process.env.ALGOLIA_API_KEY,
});
async function main() {
// Your first API call here
}
main().catch(console.error);
Python Example
from algolia import AlgoliaClient
client = AlgoliaClient()
# Your first API call here
Resources
Next Steps
Proceed to algolia-local-dev-loop for development workflow setup.
Execute Algolia incident response procedures with triage, mitigation, and postmortem.
ReadGrepBash(kubectl:*)Bash(curl:*)
Algolia Incident Runbook
Overview
Rapid incident response procedures for Algolia-related outages.
Prerequisites
- Access to Algolia dashboard and status page
- kubectl access to production cluster
- Prometheus/Grafana access
- Communication channels (Slack, PagerDuty)
Severity Levels
| Level |
Definition |
Response Time |
Examples |
| P1 |
Complete outage |
< 15 min |
Algolia API unreachable |
| P2 |
Degraded service |
< 1 hour |
High latency, partial failures |
| P3 |
Minor impact |
< 4 hours |
Webhook delays, non-critical errors |
| P4 |
No user impact |
Next business day |
Monitoring gaps |
Quick Triage
# 1. Check Algolia status
curl -s https://status.algolia.com | jq
# 2. Check our integration health
curl -s https://api.yourapp.com/health | jq '.services.algolia'
# 3. Check error rate (last 5 min)
curl -s localhost:9090/api/v1/query?query=rate(algolia_errors_total[5m])
# 4. Recent error logs
kubectl logs -l app=algolia-integration --since=5m | grep -i error | tail -20
Decision Tree
Algolia API returning errors?
├─ YES: Is status.algolia.com showing incident?
│ ├─ YES → Wait for Algolia to resolve. Enable fallback.
│ └─ NO → Our integration issue. Check credentials, config.
└─ NO: Is our service healthy?
├─ YES → Likely resolved or intermittent. Monitor.
└─ NO → Our infrastructure issue. Check pods, memory, network.
Immediate Actions by Error Type
401/403 - Authentication
# Verify API key is set
kubectl get secret algolia-secrets -o jsonpath='{.data.api-key}' | base64 -d
# Check if key was rotated
# → Verify in Algolia dashboard
# Remediation: Update secret and restart pods
kubectl create secret generic algolia-secrets --from-literal=api-key=NEW_KEY --dry-run=client -o yaml | kubectl apply -f -
kubectl rollout restart deployment/algolia-integration
429 - Rate Limited
# Check rate limit headers
curl -v https://api.algolia.com 2>&1 | grep -i rate
# Enable request queuing
kubectl set env deployment/algolia-integration RATE_LIMIT_MODE=queue
# Long-term: Contact Algolia for limit increase
500/503 - Algolia Errors
# Enable graceful degradation
kubectl set env deployment/algolia-integration ALGOLIA_FALLBACK=true
# Notify users of degraded service
# Update status page
# Monitor Algolia status for resolution
Communication Templates
Internal (Slack)
🔴 P1 INCIDENT: Algolia Integration
Status: INVESTIGATING
Impact: [Describe us
Install and configure Algolia SDK/CLI authentication.
ReadWriteEditBash(npm:*)Bash(pip:*)Grep
Algolia Install & Auth
Overview
Set up Algolia SDK/CLI and configure authentication credentials.
Prerequisites
- Node.js 18+ or Python 3.10+
- Package manager (npm, pnpm, or pip)
- Algolia account with API access
- API key from Algolia dashboard
Instructions
Step 1: Install SDK
# Node.js
npm install @algolia/sdk
# Python
pip install algolia
Step 2: Configure Authentication
# Set environment variable
export ALGOLIA_API_KEY="your-api-key"
# Or create .env file
echo 'ALGOLIA_API_KEY=your-api-key' >> .env
Step 3: Verify Connection
// Test connection code here
Output
- Installed SDK package in node_modules or site-packages
- Environment variable or .env file with API key
- Successful connection verification output
Error Handling
| Error |
Cause |
Solution |
| Invalid API Key |
Incorrect or expired key |
Verify key in Algolia dashboard |
| Rate Limited |
Exceeded quota |
Check quota at https://docs.algolia.com |
| Network Error |
Firewall blocking |
Ensure outbound HTTPS allowed |
| Module Not Found |
Installation failed |
Run npm install or pip install again |
Examples
TypeScript Setup
import { AlgoliaClient } from '@algolia/sdk';
const client = new AlgoliaClient({
apiKey: process.env.ALGOLIA_API_KEY,
});
Python Setup
from algolia import AlgoliaClient
client = AlgoliaClient(
api_key=os.environ.get('ALGOLIA_API_KEY')
)
Resources
Next Steps
After successful auth, proceed to algolia-hello-world for your first API call.
Configure Algolia local development with hot reload and testing.
ReadWriteEditBash(npm:*)Bash(pnpm:*)Grep
Algolia Local Dev Loop
Overview
Set up a fast, reproducible local development workflow for Algolia.
Prerequisites
- Completed
algolia-install-auth setup
- Node.js 18+ with npm/pnpm
- Code editor with TypeScript support
- Git for version control
Instructions
Step 1: Create Project Structure
my-algolia-project/
├── src/
│ ├── algolia/
│ │ ├── client.ts # Algolia client wrapper
│ │ ├── config.ts # Configuration management
│ │ └── utils.ts # Helper functions
│ └── index.ts
├── tests/
│ └── algolia.test.ts
├── .env.local # Local secrets (git-ignored)
├── .env.example # Template for team
└── package.json
Step 2: Configure Environment
# Copy environment template
cp .env.example .env.local
# Install dependencies
npm install
# Start development server
npm run dev
Step 3: Setup Hot Reload
{
"scripts": {
"dev": "tsx watch src/index.ts",
"test": "vitest",
"test:watch": "vitest --watch"
}
}
Step 4: Configure Testing
import { describe, it, expect, vi } from 'vitest';
import { AlgoliaClient } from '../src/algolia/client';
describe('Algolia Client', () => {
it('should initialize with API key', () => {
const client = new AlgoliaClient({ apiKey: 'test-key' });
expect(client).toBeDefined();
});
});
Output
- Working development environment with hot reload
- Configured test suite with mocking
- Environment variable management
- Fast iteration cycle for Algolia development
Error Handling
| Error |
Cause |
Solution |
| Module not found |
Missing dependency |
Run npm install |
| Port in use |
Another process |
Kill process or change port |
| Env not loaded |
Missing .env.local |
Copy from .env.example |
| Test timeout |
Slow network |
Increase test timeout |
Examples
Mock Algolia Responses
vi.mock('@algolia/sdk', () => ({
AlgoliaClient: vi.fn().mockImplementation(() => ({
// Mock methods here
})),
}));
Debug Mode
# Enable verbose logging
DEBUG=ALGOLIA=* npm run dev
Resources
Execute Algolia major re-architecture and migration strategies with strangler fig pattern.
ReadWriteEditBash(npm:*)Bash(node:*)Bash(kubectl:*)
Algolia Migration Deep Dive
Overview
Comprehensive guide for migrating to or from Algolia, or major version upgrades.
Prerequisites
- Current system documentation
- Algolia SDK installed
- Feature flag infrastructure
- Rollback strategy tested
Migration Types
| Type |
Complexity |
Duration |
Risk |
| Fresh install |
Low |
Days |
Low |
| From competitor |
Medium |
Weeks |
Medium |
| Major version |
Medium |
Weeks |
Medium |
| Full replatform |
High |
Months |
High |
Pre-Migration Assessment
Step 1: Current State Analysis
# Document current implementation
find . -name "*.ts" -o -name "*.py" | xargs grep -l "algolia" > algolia-files.txt
# Count integration points
wc -l algolia-files.txt
# Identify dependencies
npm list | grep algolia
pip freeze | grep algolia
Step 2: Data Inventory
interface MigrationInventory {
dataTypes: string[];
recordCounts: Record<string, number>;
dependencies: string[];
integrationPoints: string[];
customizations: string[];
}
async function assessAlgoliaMigration(): Promise<MigrationInventory> {
return {
dataTypes: await getDataTypes(),
recordCounts: await getRecordCounts(),
dependencies: await analyzeDependencies(),
integrationPoints: await findIntegrationPoints(),
customizations: await documentCustomizations(),
};
}
Migration Strategy: Strangler Fig Pattern
Phase 1: Parallel Run
┌─────────────┐ ┌─────────────┐
│ Old │ │ New │
│ System │ ──▶ │ Algolia │
│ (100%) │ │ (0%) │
└─────────────┘ └─────────────┘
Phase 2: Gradual Shift
┌─────────────┐ ┌─────────────┐
│ Old │ │ New │
│ (50%) │ ──▶ │ (50%) │
└─────────────┘ └─────────────┘
Phase 3: Complete
┌─────────────┐ ┌─────────────┐
│ Old │ │ New │
│ (0%) │ ──▶ │ (100%) │
└─────────────┘ └─────────────┘
Implementation Plan
Phase 1: Setup (Week 1-2)
# Install Algolia SDK
npm install @algolia/sdk
# Configure credentials
cp .env.example .env.algolia
# Edit with new credentials
# Verify connectivity
node -e "require('@algolia/sdk').ping()"
Phase 2: Adapter Layer (Week 3-4)
// src/adapters/algolia.ts
interface ServiceAdapter {
create(data: CreateInput): Promise<Resource>;
read(id: string): Promise<Resource>;
update(id: string, data: UpdateInput): Promise<Resource>;
d
Configure Algolia across development, staging, and production environments.
ReadWriteEditBash(aws:*)Bash(gcloud:*)Bash(vault:*)
Algolia Multi-Environment Setup
Overview
Configure Algolia across development, staging, and production environments.
Prerequisites
- Separate Algolia accounts or API keys per environment
- Secret management solution (Vault, AWS Secrets Manager, etc.)
- CI/CD pipeline with environment variables
- Environment detection in application
Environment Strategy
| Environment |
Purpose |
API Keys |
Data |
| Development |
Local dev |
Test keys |
Sandbox |
| Staging |
Pre-prod validation |
Staging keys |
Test data |
| Production |
Live traffic |
Production keys |
Real data |
Configuration Structure
config/
├── algolia/
│ ├── base.json # Shared config
│ ├── development.json # Dev overrides
│ ├── staging.json # Staging overrides
│ └── production.json # Prod overrides
base.json
{
"timeout": 30000,
"retries": 3,
"cache": {
"enabled": true,
"ttlSeconds": 60
}
}
development.json
{
"apiKey": "${ALGOLIA_API_KEY}",
"baseUrl": "https://api-sandbox.algolia.com",
"debug": true,
"cache": {
"enabled": false
}
}
staging.json
{
"apiKey": "${ALGOLIA_API_KEY_STAGING}",
"baseUrl": "https://api-staging.algolia.com",
"debug": false
}
production.json
{
"apiKey": "${ALGOLIA_API_KEY_PROD}",
"baseUrl": "https://api.algolia.com",
"debug": false,
"retries": 5
}
Environment Detection
// src/algolia/config.ts
import baseConfig from '../../config/algolia/base.json';
type Environment = 'development' | 'staging' | 'production';
function detectEnvironment(): Environment {
const env = process.env.NODE_ENV || 'development';
const validEnvs: Environment[] = ['development', 'staging', 'production'];
return validEnvs.includes(env as Environment)
? (env as Environment)
: 'development';
}
export function getAlgoliaConfig() {
const env = detectEnvironment();
const envConfig = require(`../../config/algolia/${env}.json`);
return {
...baseConfig,
...envConfig,
environment: env,
};
}
Secret Management by Environment
Local Development
# .env.local (git-ignored)
ALGOLIA_API_KEY=sk_tes
Set up comprehensive observability for Algolia integrations with metrics, traces, and alerts.
ReadWriteEdit
Algolia Observability
Overview
Set up comprehensive observability for Algolia integrations.
Prerequisites
- Prometheus or compatible metrics backend
- OpenTelemetry SDK installed
- Grafana or similar dashboarding tool
- AlertManager configured
Metrics Collection
Key Metrics
| Metric |
Type |
Description |
algoliarequeststotal |
Counter |
Total API requests |
algoliarequestduration_seconds |
Histogram |
Request latency |
algoliaerrorstotal |
Counter |
Error count by type |
algoliaratelimit_remaining |
Gauge |
Rate limit headroom |
Prometheus Metrics
import { Registry, Counter, Histogram, Gauge } from 'prom-client';
const registry = new Registry();
const requestCounter = new Counter({
name: 'algolia_requests_total',
help: 'Total Algolia API requests',
labelNames: ['method', 'status'],
registers: [registry],
});
const requestDuration = new Histogram({
name: 'algolia_request_duration_seconds',
help: 'Algolia request duration',
labelNames: ['method'],
buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
registers: [registry],
});
const errorCounter = new Counter({
name: 'algolia_errors_total',
help: 'Algolia errors by type',
labelNames: ['error_type'],
registers: [registry],
});
Instrumented Client
async function instrumentedRequest<T>(
method: string,
operation: () => Promise<T>
): Promise<T> {
const timer = requestDuration.startTimer({ method });
try {
const result = await operation();
requestCounter.inc({ method, status: 'success' });
return result;
} catch (error: any) {
requestCounter.inc({ method, status: 'error' });
errorCounter.inc({ error_type: error.code || 'unknown' });
throw error;
} finally {
timer();
}
}
Distributed Tracing
OpenTelemetry Setup
import { trace, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('algolia-client');
async function tracedAlgoliaCall<T>(
operationName: string,
operation: () => Promise<T>
): Promise<T> {
return tracer.startActiveSpan(`algolia.${operationName}`, async (span) => {
try {
const result = await operation();
span.setStatus({ code: SpanStatusCode.OK });
return result;
} catch (error: any) {
span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
Optimize Algolia API performance with caching, batching, and connection pooling.
ReadWriteEdit
Algolia Performance Tuning
Overview
Optimize Algolia API performance with caching, batching, and connection pooling.
Prerequisites
- Algolia SDK installed
- Understanding of async patterns
- Redis or in-memory cache available (optional)
- Performance monitoring in place
Latency Benchmarks
| Operation |
P50 |
P95 |
P99 |
| Read |
50ms |
150ms |
300ms |
| Write |
100ms |
250ms |
500ms |
| List |
75ms |
200ms |
400ms |
Caching Strategy
Response Caching
import { LRUCache } from 'lru-cache';
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 60000, // 1 minute
updateAgeOnGet: true,
});
async function cachedAlgoliaRequest<T>(
key: string,
fetcher: () => Promise<T>,
ttl?: number
): Promise<T> {
const cached = cache.get(key);
if (cached) return cached as T;
const result = await fetcher();
cache.set(key, result, { ttl });
return result;
}
Redis Caching (Distributed)
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
async function cachedWithRedis<T>(
key: string,
fetcher: () => Promise<T>,
ttlSeconds = 60
): Promise<T> {
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const result = await fetcher();
await redis.setex(key, ttlSeconds, JSON.stringify(result));
return result;
}
Request Batching
import DataLoader from 'dataloader';
const algoliaLoader = new DataLoader<string, any>(
async (ids) => {
// Batch fetch from Algolia
const results = await algoliaClient.batchGet(ids);
return ids.map(id => results.find(r => r.id === id) || null);
},
{
maxBatchSize: 100,
batchScheduleFn: callback => setTimeout(callback, 10),
}
);
// Usage - automatically batched
const [item1, item2, item3] = await Promise.all([
algoliaLoader.load('id-1'),
algoliaLoader.load('id-2'),
algoliaLoader.load('id-3'),
]);
Connection Optimization
import { Agent } from 'https';
// Keep-alive connection pooling
const agent = new Agent({
keepAlive: true,
maxSockets: 10,
maxFreeSockets: 5,
timeout: 30000,
});
const client = new AlgoliaClient({
apiKey: process.env.ALGOLIA_API_KEY!,
httpAgent: agent,
});
Pagination Optimization
async function* paginatedAlgoliaList<T>(
fetcher: (cursor?: string) => Promise<{ data: T[]; nextCursor?: string }>
): AsyncGenerator<T
Execute Algolia production deployment checklist and rollback procedures.
ReadBash(kubectl:*)Bash(curl:*)Grep
Algolia Production Checklist
Overview
Complete checklist for deploying Algolia integrations to production.
Prerequisites
- Staging environment tested and verified
- Production API keys available
- Deployment pipeline configured
- Monitoring and alerting ready
Instructions
Step 1: Pre-Deployment Configuration
- [ ] Production API keys in secure vault
- [ ] Environment variables set in deployment platform
- [ ] API key scopes are minimal (least privilege)
- [ ] Webhook endpoints configured with HTTPS
- [ ] Webhook secrets stored securely
Step 2: Code Quality Verification
- [ ] All tests passing (
npm test)
- [ ] No hardcoded credentials
- [ ] Error handling covers all Algolia error types
- [ ] Rate limiting/backoff implemented
- [ ] Logging is production-appropriate
Step 3: Infrastructure Setup
- [ ] Health check endpoint includes Algolia connectivity
- [ ] Monitoring/alerting configured
- [ ] Circuit breaker pattern implemented
- [ ] Graceful degradation configured
Step 4: Documentation Requirements
- [ ] Incident runbook created
- [ ] Key rotation procedure documented
- [ ] Rollback procedure documented
- [ ] On-call escalation path defined
Step 5: Deploy with Gradual Rollout
# Pre-flight checks
curl -f https://staging.example.com/health
curl -s https://status.algolia.com
# Gradual rollout - start with canary (10%)
kubectl apply -f k8s/production.yaml
kubectl set image deployment/algolia-integration app=image:new --record
kubectl rollout pause deployment/algolia-integration
# Monitor canary traffic for 10 minutes
sleep 600
# Check error rates and latency before continuing
# If healthy, continue rollout to 50%
kubectl rollout resume deployment/algolia-integration
kubectl rollout pause deployment/algolia-integration
sleep 300
# Complete rollout to 100%
kubectl rollout resume deployment/algolia-integration
kubectl rollout status deployment/algolia-integration
Output
- Deployed Algolia integration
- Health checks passing
- Monitoring active
- Rollback procedure documented
Error Handling
| Alert |
Condition |
Severity |
| API Down |
5xx errors > 10/min |
P1 |
| High Latency |
p99 > 5000ms |
P2 |
| Rate Limited |
429 errors > 5/min |
P2 |
| Auth Failures |
401/403 errors > 0 |
P1 |
Examples
Health Check Implementation
async function healthCheck(): Promise<{ status: string; algolia: any }> {
cons
Implement Algolia rate limiting, backoff, and idempotency patterns.
ReadWriteEdit
Algolia Rate Limits
Overview
Handle Algolia rate limits gracefully with exponential backoff and idempotency.
Prerequisites
- Algolia SDK installed
- Understanding of async/await patterns
- Access to rate limit headers
Instructions
Step 1: Understand Rate Limit Tiers
| Tier |
Requests/min |
Requests/day |
Burst |
| Free |
60 |
1,000 |
10 |
| Pro |
300 |
10,000 |
50 |
| Enterprise |
1,000 |
100,000 |
200 |
Step 2: Implement Exponential Backoff with Jitter
async function withExponentialBackoff<T>(
operation: () => Promise<T>,
config = { maxRetries: 5, baseDelayMs: 1000, maxDelayMs: 32000, jitterMs: 500 }
): Promise<T> {
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (error: any) {
if (attempt === config.maxRetries) throw error;
const status = error.status || error.response?.status;
if (status !== 429 && (status < 500 || status >= 600)) throw error;
// Exponential delay with jitter to prevent thundering herd
const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);
const jitter = Math.random() * config.jitterMs;
const delay = Math.min(exponentialDelay + jitter, config.maxDelayMs);
console.log(`Rate limited. Retrying in ${delay.toFixed(0)}ms...`);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}
Step 3: Add Idempotency Keys
import { v4 as uuidv4 } from 'uuid';
import crypto from 'crypto';
// Generate deterministic key from operation params (for safe retries)
function generateIdempotencyKey(operation: string, params: Record<string, any>): string {
const data = JSON.stringify({ operation, params });
return crypto.createHash('sha256').update(data).digest('hex');
}
async function idempotentRequest<T>(
client: AlgoliaClient,
params: Record<string, any>,
idempotencyKey?: string // Pass existing key for retries
): Promise<T> {
// Use provided key (for retries) or generate deterministic key from params
const key = idempotencyKey || generateIdempotencyKey(params.method || 'POST', params);
return client.request({
...params,
headers: { 'Idempotency-Key': key, ...params.headers },
});
}
Output
- Reliable API calls with automatic retry
- Idempotent requests preventing duplicates
- Rate limit headers properly handled
Error Handling
| Header |
Description |
Action
Implement Algolia reference architecture with best-practice project layout.
ReadGrep
Algolia Reference Architecture
Overview
Production-ready architecture patterns for Algolia integrations.
Prerequisites
- Understanding of layered architecture
- Algolia SDK knowledge
- TypeScript project setup
- Testing framework configured
Project Structure
my-algolia-project/
├── src/
│ ├── algolia/
│ │ ├── client.ts # Singleton client wrapper
│ │ ├── config.ts # Environment configuration
│ │ ├── types.ts # TypeScript types
│ │ ├── errors.ts # Custom error classes
│ │ └── handlers/
│ │ ├── webhooks.ts # Webhook handlers
│ │ └── events.ts # Event processing
│ ├── services/
│ │ └── algolia/
│ │ ├── index.ts # Service facade
│ │ ├── sync.ts # Data synchronization
│ │ └── cache.ts # Caching layer
│ ├── api/
│ │ └── algolia/
│ │ └── webhook.ts # Webhook endpoint
│ └── jobs/
│ └── algolia/
│ └── sync.ts # Background sync job
├── tests/
│ ├── unit/
│ │ └── algolia/
│ └── integration/
│ └── algolia/
├── config/
│ ├── algolia.development.json
│ ├── algolia.staging.json
│ └── algolia.production.json
└── docs/
└── algolia/
├── SETUP.md
└── RUNBOOK.md
Layer Architecture
┌─────────────────────────────────────────┐
│ API Layer │
│ (Controllers, Routes, Webhooks) │
├─────────────────────────────────────────┤
│ Service Layer │
│ (Business Logic, Orchestration) │
├─────────────────────────────────────────┤
│ Algolia Layer │
│ (Client, Types, Error Handling) │
├─────────────────────────────────────────┤
│ Infrastructure Layer │
│ (Cache, Queue, Monitoring) │
└─────────────────────────────────────────┘
Key Components
Step 1: Client Wrapper
// src/algolia/client.ts
export class AlgoliaService {
private client: AlgoliaClient;
private cache: Cache;
private monitor: Monitor;
constructor(config: AlgoliaConfig) {
this.client = new AlgoliaClient(config);
this.cache = new Cache(config.cacheOptions);
this.monitor = new Monitor('algolia');
}
async get(id: string): Promise<Resource> {
return this.cache.getOrFetch(id, () =>
this.monitor.track('get', () => this.client.get(id))
);
}
}
Step 2: Error Boundary
// src/algolia/errors.ts
export class AlgoliaServiceError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly retryable: boolean,
public readonly originalError?: Error
) {
super(message);
this.name = 'AlgoliaServiceError';
}
Apply production-ready Algolia SDK patterns for TypeScript and Python.
ReadWriteEdit
Algolia SDK Patterns
Overview
Production-ready patterns for Algolia SDK usage in TypeScript and Python.
Prerequisites
- Completed
algolia-install-auth setup
- Familiarity with async/await patterns
- Understanding of error handling best practices
Instructions
Step 1: Implement Singleton Pattern (Recommended)
// src/algolia/client.ts
import { AlgoliaClient } from '@algolia/sdk';
let instance: AlgoliaClient | null = null;
export function getAlgoliaClient(): AlgoliaClient {
if (!instance) {
instance = new AlgoliaClient({
apiKey: process.env.ALGOLIA_API_KEY!,
// Additional options
});
}
return instance;
}
Step 2: Add Error Handling Wrapper
import { AlgoliaError } from '@algolia/sdk';
async function safeAlgoliaCall<T>(
operation: () => Promise<T>
): Promise<{ data: T | null; error: Error | null }> {
try {
const data = await operation();
return { data, error: null };
} catch (err) {
if (err instanceof AlgoliaError) {
console.error({
code: err.code,
message: err.message,
});
}
return { data: null, error: err as Error };
}
}
Step 3: Implement Retry Logic
async function withRetry<T>(
operation: () => Promise<T>,
maxRetries = 3,
backoffMs = 1000
): Promise<T> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (err) {
if (attempt === maxRetries) throw err;
const delay = backoffMs * Math.pow(2, attempt - 1);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}
Output
- Type-safe client singleton
- Robust error handling with structured logging
- Automatic retry with exponential backoff
- Runtime validation for API responses
Error Handling
| Pattern |
Use Case |
Benefit |
| Safe wrapper |
All API calls |
Prevents uncaught exceptions |
| Retry logic |
Transient failures |
Improves reliability |
| Type guards |
Response validation |
Catches API changes |
| Logging |
All operations |
Debugging and monitoring |
Examples
Factory Pattern (Multi-tenant)
const clients = new Map<string, AlgoliaClient>();
export function getClientForTenant(tenantId: string): AlgoliaClient {
if (!clients.has(tenantId)) {
const apiKey = getTenantApiKey(tenantId);
clients.set(tenantId, new AlgoliaClient({ apiKey }));
}
return clients
Apply Algolia security best practices for secrets and access control.
ReadWriteGrep
Algolia Security Basics
Overview
Security best practices for Algolia API keys, tokens, and access control.
Prerequisites
- Algolia SDK installed
- Understanding of environment variables
- Access to Algolia dashboard
Instructions
Step 1: Configure Environment Variables
# .env (NEVER commit to git)
ALGOLIA_API_KEY=sk_live_***
ALGOLIA_SECRET=***
# .gitignore
.env
.env.local
.env.*.local
Step 2: Implement Secret Rotation
# 1. Generate new key in Algolia dashboard
# 2. Update environment variable
export ALGOLIA_API_KEY="new_key_here"
# 3. Verify new key works
curl -H "Authorization: Bearer ${ALGOLIA_API_KEY}" \
https://api.algolia.com/health
# 4. Revoke old key in dashboard
Step 3: Apply Least Privilege
| Environment |
Recommended Scopes |
| Development |
read:* |
| Staging |
read:*, write:limited |
| Production |
Only required scopes |
Output
- Secure API key storage
- Environment-specific access controls
- Audit logging enabled
Error Handling
| Security Issue |
Detection |
Mitigation |
| Exposed API key |
Git scanning |
Rotate immediately |
| Excessive scopes |
Audit logs |
Reduce permissions |
| Missing rotation |
Key age check |
Schedule rotation |
Examples
Service Account Pattern
const clients = {
reader: new AlgoliaClient({
apiKey: process.env.ALGOLIA_READ_KEY,
}),
writer: new AlgoliaClient({
apiKey: process.env.ALGOLIA_WRITE_KEY,
}),
};
Webhook Signature Verification
import crypto from 'crypto';
function verifyWebhookSignature(
payload: string, signature: string, secret: string
): boolean {
const expected = crypto.createHmac('sha256', secret).update(payload).digest('hex');
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
Security Checklist
- [ ] API keys in environment variables
- [ ]
.env files in .gitignore
- [ ] Different keys for dev/staging/prod
- [ ] Minimal scopes per environment
- [ ] Webhook signatures validated
- [ ] Audit logging enabled
Audit Logging
interface AuditEntry {
timestamp: Date;
action: string;
userId: string;
resource: string;
result: 'success' | 'failure';
metadata?: Re
Analyze, plan, and execute Algolia SDK upgrades with breaking change detection.
ReadWriteEditBash(npm:*)Bash(git:*)
Algolia Upgrade & Migration
Overview
Guide for upgrading Algolia SDK versions and handling breaking changes.
Prerequisites
- Current Algolia SDK installed
- Git for version control
- Test suite available
- Staging environment
Instructions
Step 1: Check Current Version
npm list @algolia/sdk
npm view @algolia/sdk version
Step 2: Review Changelog
open https://github.com/algolia/sdk/releases
Step 3: Create Upgrade Branch
git checkout -b upgrade/algolia-sdk-vX.Y.Z
npm install @algolia/sdk@latest
npm test
Step 4: Handle Breaking Changes
Update import statements, configuration, and method signatures as needed.
Output
- Updated SDK version
- Fixed breaking changes
- Passing test suite
- Documented rollback procedure
Error Handling
| SDK Version |
API Version |
Node.js |
Breaking Changes |
| 3.x |
2024-01 |
18+ |
Major refactor |
| 2.x |
2023-06 |
16+ |
Auth changes |
| 1.x |
2022-01 |
14+ |
Initial release |
Examples
Import Changes
// Before (v1.x)
import { Client } from '@algolia/sdk';
// After (v2.x)
import { AlgoliaClient } from '@algolia/sdk';
Configuration Changes
// Before (v1.x)
const client = new Client({ key: 'xxx' });
// After (v2.x)
const client = new AlgoliaClient({
apiKey: 'xxx',
});
Rollback Procedure
npm install @algolia/sdk@1.x.x --save-exact
Deprecation Handling
// Monitor for deprecation warnings in development
if (process.env.NODE_ENV === 'development') {
process.on('warning', (warning) => {
if (warning.name === 'DeprecationWarning') {
console.warn('[Algolia]', warning.message);
// Log to tracking system for proactive updates
}
});
}
// Common deprecation patterns to watch for:
// - Renamed methods: client.oldMethod() -> client.newMethod()
// - Changed parameters: { key: 'x' } -> { apiKey: 'x' }
// - Removed features: Check release notes before upgrading
Resources
Next Steps
For CI integration during upgrades, see algolia-ci-integration.
Implement Algolia webhook signature validation and event handling.
ReadWriteEditBash(curl:*)
Algolia Webhooks & Events
Overview
Securely handle Algolia webhooks with signature validation and replay protection.
Prerequisites
- Algolia webhook secret configured
- HTTPS endpoint accessible from internet
- Understanding of cryptographic signatures
- Redis or database for idempotency (optional)
Webhook Endpoint Setup
Express.js
import express from 'express';
import crypto from 'crypto';
const app = express();
// IMPORTANT: Raw body needed for signature verification
app.post('/webhooks/algolia',
express.raw({ type: 'application/json' }),
async (req, res) => {
const signature = req.headers['x-algolia-signature'] as string;
const timestamp = req.headers['x-algolia-timestamp'] as string;
if (!verifyAlgoliaSignature(req.body, signature, timestamp)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const event = JSON.parse(req.body.toString());
await handleAlgoliaEvent(event);
res.status(200).json({ received: true });
}
);
Signature Verification
function verifyAlgoliaSignature(
payload: Buffer,
signature: string,
timestamp: string
): boolean {
const secret = process.env.ALGOLIA_WEBHOOK_SECRET!;
// Reject old timestamps (replay attack protection)
const timestampAge = Date.now() - parseInt(timestamp) * 1000;
if (timestampAge > 300000) { // 5 minutes
console.error('Webhook timestamp too old');
return false;
}
// Compute expected signature
const signedPayload = `${timestamp}.${payload.toString()}`;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload)
.digest('hex');
// Timing-safe comparison
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}
Event Handler Pattern
type AlgoliaEventType = 'resource.created' | 'resource.updated' | 'resource.deleted';
interface AlgoliaEvent {
id: string;
type: AlgoliaEventType;
data: Record<string, any>;
created: string;
}
const eventHandlers: Record<AlgoliaEventType, (data: any) => Promise<void>> = {
'resource.created': async (data) => { /* handle */ },
'resource.updated': async (data) => { /* handle */ },
'resource.deleted': async (data) => { /* handle */ }
};
async function handleAlgoliaEvent(event: AlgoliaEvent): Promise<void> {
const handler = eventHandlers[event.type];
if (!handler) {
console.log(`Unhandled event type: ${event.type}`);
return;
}
try {
await handler(event.data);
console.log(`Processed ${event.type}: ${event.id}`);
} catch (error) {
console.error(`Failed to proc
Ready to use algolia-pack?
|
|