Complete Examples
Production-ready service implementations with full code, patterns, and best practices
Production-ready service implementations demonstrating real-world patterns, best practices, and complete workflows from input to monetization.
Overview
These examples showcase complete, end-to-end service implementations that you can use as templates for your own services. Each example includes:
- Complete Service Definition - Full specifications, schemas, and pricing
- Implementation Code - Production-ready service logic
- Error Handling - Robust error recovery and validation
- Testing Strategy - Unit, integration, and E2E tests
- Monitoring Setup - Metrics, logging, and alerting
- Pricing Model - Real-world monetization strategy
- Best Practices - Proven patterns and optimizations
Example Categories
| Example | Category | Complexity | Revenue Model | Time to Implement |
|---|---|---|---|---|
| Content Service | AI Services | Intermediate | $29-99/post | 1-2 weeks |
| Analysis Service | Data Services | Intermediate | $25/analysis | 1-2 weeks |
| Workflow Service | Automation | Advanced | $1-2/invoice | 2-3 weeks |
| Integration Service | Integration | Advanced | $99-999/month | 2-4 weeks |
Content Generation Example
Build an AI-powered blog post generator with research, writing, optimization, and delivery.
What You'll Learn
- Multi-stage AI content generation pipelines
- Quality assurance with automated checks
- Tiered pricing models
- Image generation integration
- SEO optimization workflows
- Content delivery and formatting
Service Overview
const blogGeneratorService = {
name: 'AI Blog Post Generator',
type: $.ServiceType.ContentGeneration,
stages: ['keyword-research', 'topic-selection', 'outline-creation', 'content-writing', 'seo-optimization', 'image-generation', 'quality-assurance'],
pricing: {
model: 'tiered',
tiers: [
{ name: 'basic', price: 29, wordCount: 800, images: 1 },
{ name: 'standard', price: 49, wordCount: 1500, images: 3 },
{ name: 'premium', price: 99, wordCount: 2500, images: 5 },
],
},
}Key Features Demonstrated
- AI Pipeline: Multi-step content generation workflow
- Quality Gates: Automated readability and SEO checks
- Resource Management: Image generation and optimization
- Dynamic Pricing: Tier-based pricing with feature gating
- Result Delivery: Structured output with metadata
Revenue Potential
- Price Range: $29-99 per blog post
- Target Market: Content marketers, agencies, businesses
- Volume: 10-50 posts per customer per month
- Monthly Revenue: $290-4,950 per customer
View Complete Content Service Example →
Data Analysis Example
Build an automated sales data analysis service with insights, predictions, and reporting.
What You'll Learn
- Data aggregation and transformation
- AI-powered analysis and insights
- Automated report generation
- Visualization and charting
- Scheduled and on-demand execution
- Result caching and optimization
Service Overview
const analysisService = {
name: 'Sales Data Analyzer',
type: $.ServiceType.DataAnalysis,
analyses: ['trend-analysis', 'anomaly-detection', 'predictive-modeling', 'customer-segmentation', 'revenue-forecasting'],
pricing: {
model: 'per-analysis',
rate: 25.0,
currency: 'USD',
},
}Key Features Demonstrated
- Data Processing: Query and aggregate large datasets
- AI Analysis: Generate insights and recommendations
- Report Generation: PDF/HTML report creation
- Caching Strategy: Optimize repeat analyses
- Webhook Integration: Deliver results asynchronously
Revenue Potential
- Price: $25 per analysis
- Target Market: Sales teams, business analysts, executives
- Volume: 20-100 analyses per customer per month
- Monthly Revenue: $500-2,500 per customer
View Complete Analysis Service Example →
Automation Workflow Example
Build an end-to-end invoice processing automation with OCR, validation, approval routing, and payment.
What You'll Learn
- Document processing with AI OCR
- Multi-stage validation workflows
- Approval routing and human-in-the-loop
- Integration with accounting systems
- Error recovery and retry logic
- Volume-based pricing
Service Overview
const invoiceAutomationService = {
name: 'Automated Invoice Processor',
type: $.ServiceType.Automation,
workflow: ['invoice-receipt', 'data-extraction', 'validation', 'po-matching', 'approval-routing', 'payment-scheduling', 'accounting-integration'],
pricing: {
model: 'per-invoice',
tiers: [
{ min: 0, max: 100, rate: 2.0 },
{ min: 101, max: 500, rate: 1.5 },
{ min: 501, max: Infinity, rate: 1.0 },
],
},
}Key Features Demonstrated
- OCR Integration: Extract structured data from documents
- Validation Logic: Multi-level validation checks
- State Machine: Complex workflow orchestration
- Human Review: Human-in-the-loop for edge cases
- System Integration: Connect to ERPs and accounting systems
- Volume Discounts: Automatic pricing tiers
Revenue Potential
- Price Range: $1-2 per invoice
- Target Market: Mid to large businesses, accounting firms
- Volume: 500-5,000 invoices per customer per month
- Monthly Revenue: $500-10,000 per customer
- ROI: Saves 10-15 minutes per invoice in manual work
View Complete Workflow Service Example →
CRM Integration Example
Build a universal CRM synchronization service supporting multiple platforms with bidirectional sync.
What You'll Learn
- Multi-platform integration architecture
- Bidirectional data synchronization
- Conflict resolution strategies
- Real-time vs. batch sync patterns
- Field mapping and transformation
- Subscription-based pricing
Service Overview
const crmSyncService = {
name: 'Universal CRM Synchronizer',
type: $.ServiceType.Integration,
platforms: ['salesforce', 'hubspot', 'pipedrive', 'zoho', 'dynamics'],
pricing: {
model: 'subscription',
tiers: [
{
name: 'starter',
price: 99,
recordLimit: 10000,
syncFrequency: 'hourly',
},
{
name: 'professional',
price: 299,
recordLimit: 100000,
syncFrequency: 'real-time',
},
{
name: 'enterprise',
price: 999,
recordLimit: Infinity,
syncFrequency: 'real-time',
customMappings: true,
},
],
},
}Key Features Demonstrated
- Multi-Platform: Support for 5+ CRM platforms
- Bidirectional Sync: Changes flow both directions
- Conflict Resolution: Handle concurrent updates
- Field Mapping: Custom field transformation
- Rate Limiting: Respect API limits
- Subscription Management: Recurring billing integration
Revenue Potential
- Price Range: $99-999 per month
- Target Market: Businesses using multiple CRMs
- Churn Rate: Low (high switching costs)
- Monthly Revenue: $99-999 per customer
- Annual Contract Value: $1,188-11,988
View Complete Integration Service Example →
Content Services
Example 1: Blog Post Generator
Complete blog creation from topic to publication:
import $, { ai, db, on, send } from 'sdk.do'
const blogGeneratorService = await $.Service.create({
name: 'AI Blog Post Generator',
type: $.ServiceType.ContentGeneration,
workflow: ['keyword-research', 'topic-selection', 'outline-creation', 'content-writing', 'seo-optimization', 'image-generation', 'quality-assurance'],
pricing: {
model: 'per-post',
tiers: [
{ name: 'basic', price: 29, length: 800, images: 1 },
{ name: 'standard', price: 49, length: 1500, images: 3 },
{ name: 'premium', price: 99, length: 2500, images: 5, research: 'deep' },
],
},
})
on.ServiceRequest.created, async (request) => {
if (request.serviceId !== blogGeneratorService.id) return
const tier = request.inputs.tier || 'standard'
const config = blogGeneratorService.pricing.tiers.find((t) => t.name === tier)
try {
// 1. Keyword Research
const keywords = await ai.research({
model: 'gpt-5',
topic: request.inputs.topic,
industry: request.inputs.industry,
intent: 'informational',
count: 10,
})
// 2. Select Best Topics
const topicAnalysis = await ai.analyze({
model: 'gpt-5',
keywords,
criteria: ['search-volume', 'competition', 'relevance'],
selectTop: 1,
})
// 3. Create Outline
const outline = await ai.generate({
model: 'gpt-5',
type: 'blog-outline',
context: {
topic: topicAnalysis.selectedTopic,
keywords: keywords.primary,
targetLength: config.length,
audience: request.inputs.audience,
},
})
// 4. Write Content
const content = await ai.generate({
model: 'gpt-5',
type: 'blog-post',
context: {
outline: outline.sections,
keywords: keywords.primary,
tone: request.inputs.tone || 'professional',
length: config.length,
},
quality: {
minReadability: 60,
keywordDensity: { min: 0.01, max: 0.03 },
uniqueness: 0.95,
},
})
// 5. SEO Optimization
const seo = await ai.optimize({
model: 'gpt-5',
content: content.text,
keywords: keywords.primary,
optimizations: ['meta-description', 'title-tag', 'header-hierarchy', 'internal-links', 'keyword-placement'],
})
// 6. Generate Images
const images = []
if (config.images > 0) {
const imagePrompts = await ai.generate({
model: 'gpt-5',
type: 'image-prompts',
context: { content: content.text, count: config.images },
})
for (const prompt of imagePrompts) {
const image = await ai.generateImage({
model: 'dalle-3',
prompt: prompt.text,
style: 'professional',
aspectRatio: '16:9',
})
images.push(image)
}
}
// 7. Quality Check
const quality = await ai.evaluate({
content: seo.optimizedContent,
criteria: {
readability: { min: 60 },
seoScore: { min: 80 },
grammar: { maxErrors: 3 },
plagiarism: { maxSimilarity: 0.05 },
},
})
if (quality.passed) {
// Deliver complete package
send.ServiceResult.deliver, {
requestId: request.id,
outputs: {
post: {
title: seo.title,
content: seo.optimizedContent,
excerpt: content.excerpt,
images,
seo: {
metaDescription: seo.metaDescription,
keywords: keywords.primary,
slug: seo.slug,
},
},
analytics: {
wordCount: content.wordCount,
readingTime: Math.ceil(content.wordCount / 200),
seoScore: seo.score,
readabilityScore: quality.readability,
},
research: {
keywords: keywords.all,
competitorAnalysis: keywords.competition,
},
},
format: 'markdown',
})
// Bill for service
send.Payment.charge, {
customerId: request.customerId,
amount: config.price,
description: `Blog Post (${tier} tier) - ${seo.title}`,
})
} else {
// Quality check failed, improve content
const improved = await ai.improve({
content: seo.optimizedContent,
issues: quality.issues,
})
// Deliver improved version
// ... (similar to above)
}
} catch (error) {
send.ServiceRequest.fail, {
requestId: request.id,
error: error.message,
})
}
})Key Features:
- Multi-stage content creation pipeline
- AI-powered research and writing
- Built-in SEO optimization
- Automated image generation
- Quality assurance checks
- Tiered pricing model
Revenue Model: $29-99 per blog post Target Customers: Content marketers, bloggers, agencies Estimated Time: 5-10 minutes per post
Example 2: Product Description Writer
E-commerce product description generation:
const productDescriptionService = await $.Service.create({
name: 'E-commerce Product Description Writer',
type: $.ServiceType.ContentGeneration,
pricing: {
model: 'per-product',
base: 5.0,
variables: {
length: { short: 1.0, medium: 1.5, long: 2.0 },
language: { additional: 3.0 },
},
},
})
on.ServiceRequest.created, async (request) => {
if (request.serviceId !== productDescriptionService.id) return
const product = request.inputs.product
// Analyze product
const analysis = await ai.analyze({
model: 'gpt-5',
data: {
category: product.category,
features: product.features,
specifications: product.specs,
images: product.images,
},
extract: ['key-benefits', 'unique-selling-points', 'target-audience'],
})
// Generate description
const description = await ai.generate({
model: 'gpt-5',
type: 'product-description',
context: {
productName: product.name,
analysis,
tone: 'persuasive',
length: request.inputs.length || 'medium',
keywords: product.targetKeywords,
},
})
// Generate variations for A/B testing
const variations = await Promise.all([
ai.generate({
model: 'gpt-5',
type: 'product-description',
context: { ...description, style: 'features-focused' },
}),
ai.generate({
model: 'gpt-5',
type: 'product-description',
context: { ...description, style: 'benefits-focused' },
}),
ai.generate({
model: 'gpt-5',
type: 'product-description',
context: { ...description, style: 'story-driven' },
}),
])
// Translate if requested
let translations = {}
if (request.inputs.languages) {
for (const lang of request.inputs.languages) {
translations[lang] = await ai.translate({
text: description.text,
to: lang,
preserveFormatting: true,
})
}
}
// Calculate price
const lengthMultiplier = productDescriptionService.pricing.variables.length[request.inputs.length || 'medium']
const translationCost = Object.keys(translations).length * productDescriptionService.pricing.variables.language.additional
const total = productDescriptionService.pricing.base * lengthMultiplier + translationCost
// Deliver
send.ServiceResult.deliver, {
requestId: request.id,
outputs: {
primary: description.text,
variations: variations.map((v) => v.text),
translations,
seo: {
title: description.seoTitle,
metaDescription: description.metaDescription,
},
bullets: description.keyFeatures,
},
})
send.Payment.charge, {
customerId: request.customerId,
amount: total,
breakdown: {
base: productDescriptionService.pricing.base * lengthMultiplier,
translations: translationCost,
},
})
})Key Features:
- Feature and benefit extraction
- Multiple description variations
- Multi-language support
- SEO optimization
- A/B testing variations
Revenue Model: $5-10 per description + $3 per language Target Customers: E-commerce stores, marketplace sellers Estimated Time: 1-2 minutes per product
Automation Services
Example 3: Invoice Processing Automation
End-to-end invoice automation:
const invoiceAutomationService = await $.Service.create({
name: 'Automated Invoice Processor',
type: $.ServiceType.Automation,
workflow: ['invoice-receipt', 'data-extraction', 'validation', 'po-matching', 'approval-routing', 'payment-scheduling', 'accounting-integration'],
pricing: {
model: 'per-invoice',
base: 2.0,
volume: [
{ min: 0, max: 100, rate: 2.0 },
{ min: 101, max: 500, rate: 1.5 },
{ min: 501, max: Infinity, rate: 1.0 },
],
},
})
on.Invoice.received, async (invoice) => {
try {
// 1. Extract data using AI OCR
const extracted = await ai.extract({
model: 'gpt-5',
document: invoice.file,
schema: {
vendorName: 'string',
vendorAddress: 'address',
invoiceNumber: 'string',
invoiceDate: 'date',
dueDate: 'date',
poNumber: 'string',
lineItems: [
{
description: 'string',
quantity: 'number',
unitPrice: 'currency',
amount: 'currency',
},
],
subtotal: 'currency',
tax: 'currency',
total: 'currency',
bankDetails: {
accountName: 'string',
accountNumber: 'string',
routingNumber: 'string',
},
},
})
// 2. Validate extraction
const validation = await validateInvoice(extracted)
if (!validation.valid) {
// Low confidence, send for human review
send.HumanReview.create, {
type: 'invoice-extraction',
invoiceId: invoice.id,
extracted,
issues: validation.issues,
priority: 'normal',
})
return
}
// 3. Match with purchase order
const po = await db.findOne($.PurchaseOrder, {
number: extracted.poNumber,
vendorName: extracted.vendorName,
})
if (!po) {
send.Invoice.flagForReview, {
invoiceId: invoice.id,
reason: 'No matching purchase order',
extracted,
})
return
}
// 4. Validate against PO
const poValidation = await validateAgainstPO(extracted, po)
if (!poValidation.matches) {
send.Invoice.flagForReview, {
invoiceId: invoice.id,
reason: 'Invoice does not match PO',
differences: poValidation.differences,
extracted,
po,
})
return
}
// 5. Route for approval
const approver = await determineApprover(extracted, po)
if (extracted.total > approver.approvalLimit) {
// Requires higher approval
const seniorApprover = await getNextApprover(approver)
send.Approval.request, {
type: 'invoice',
invoiceId: invoice.id,
amount: extracted.total,
approverId: seniorApprover.id,
context: { extracted, po },
})
} else {
// Auto-approve within limit
send.Approval.autoApprove, {
invoiceId: invoice.id,
approverId: approver.id,
reason: 'Within approval limit',
})
}
// 6. Create accounting entries
send.AccountingEntry.create, {
type: 'accounts-payable',
invoiceId: invoice.id,
vendor: extracted.vendorName,
amount: extracted.total,
dueDate: extracted.dueDate,
lineItems: extracted.lineItems.map((item) => ({
account: mapToGLAccount(item.description),
debit: item.amount,
})),
})
// 7. Schedule payment
const paymentDate = calculatePaymentDate(extracted.dueDate, po.paymentTerms)
send.Payment.schedule, {
payee: extracted.vendorName,
amount: extracted.total,
date: paymentDate,
method: po.paymentMethod,
bankDetails: extracted.bankDetails,
reference: extracted.invoiceNumber,
})
// 8. Update inventory
for (const item of extracted.lineItems) {
if (item.sku) {
send.Inventory.update, {
sku: item.sku,
quantity: { increment: item.quantity },
location: po.deliveryLocation,
})
}
}
// Update invoice status
await db.update(invoice, {
status: 'processed',
processedAt: new Date(),
extractedData: extracted,
purchaseOrder: po.id,
paymentScheduled: paymentDate,
})
// Bill for service
const monthlyVolume = await getMonthlyInvoiceCount(invoice.companyId)
const tier = invoiceAutomationService.pricing.volume.find((t) => monthlyVolume >= t.min && monthlyVolume <= t.max)
send.Payment.charge, {
customerId: invoice.companyId,
amount: tier.rate,
description: `Invoice Processing - ${extracted.invoiceNumber}`,
})
} catch (error) {
send.Invoice.processingFailed, {
invoiceId: invoice.id,
error: error.message,
})
}
})
// Approval workflow
on.Approval.granted, async (approval) => {
if (approval.type !== 'invoice') return
// Continue with payment
const invoice = await db.findOne($.Invoice, { id: approval.invoiceId })
send.Payment.execute, {
invoiceId: invoice.id,
})
})Key Features:
- AI-powered data extraction
- Purchase order matching
- Automated approval routing
- Payment scheduling
- Accounting integration
- Inventory updates
Revenue Model: $1-2 per invoice (volume discounts) Target Customers: Mid to large businesses, accounting firms ROI: Saves 10-15 minutes per invoice in manual processing
Data Services
Example 4: Lead Enrichment Service
Enhance lead data with AI research:
const leadEnrichmentService = await $.Service.create({
name: 'AI Lead Enricher',
type: $.ServiceType.DataEnrichment,
enrichmentLevels: {
basic: {
price: 0.25,
includes: ['email-verification', 'company-info'],
},
standard: {
price: 0.75,
includes: ['basic', 'social-profiles', 'job-details', 'company-size'],
},
premium: {
price: 1.5,
includes: ['standard', 'technographics', 'intent-data', 'org-chart'],
},
},
})
on.ServiceRequest.created, async (request) => {
if (request.serviceId !== leadEnrichmentService.id) return
const level = request.inputs.level || 'standard'
const config = leadEnrichmentService.enrichmentLevels[level]
const enrichedLeads = []
for (const lead of request.inputs.leads) {
const enriched = { ...lead }
try {
// Email verification (all levels)
enriched.email = await verifyEmail(lead.email)
// Company info (all levels)
if (lead.company || lead.domain) {
enriched.company = await ai.research({
model: 'gpt-5',
query: lead.company || lead.domain,
sources: ['linkedin', 'crunchbase', 'company-website'],
extract: ['industry', 'size', 'revenue', 'location', 'description'],
})
}
// Standard and Premium
if (config.includes.includes('social-profiles')) {
enriched.social = await findSocialProfiles(lead)
if (enriched.social.linkedin) {
enriched.jobDetails = await ai.extract({
model: 'gpt-5',
source: enriched.social.linkedin,
schema: {
title: 'string',
seniority: 'string',
department: 'string',
startDate: 'date',
previousRoles: ['string'],
},
})
}
}
// Premium only
if (config.includes.includes('technographics')) {
enriched.technographics = await ai.research({
model: 'gpt-5',
company: enriched.company,
extract: ['technologies-used', 'stack', 'tools'],
})
}
if (config.includes.includes('intent-data')) {
enriched.intent = await ai.analyze({
model: 'gpt-5',
sources: [enriched.social, enriched.company.recentNews],
indicators: ['buying-signals', 'pain-points', 'interests'],
})
}
if (config.includes.includes('org-chart')) {
enriched.orgChart = await ai.research({
model: 'gpt-5',
company: enriched.company,
findRelatedPeople: {
relationship: ['reports-to', 'team-members', 'decision-makers'],
},
})
}
// Lead scoring
enriched.score = await ai.score({
model: 'gpt-5',
lead: enriched,
criteria: request.inputs.scoringCriteria || 'default',
scale: 100,
})
enrichedLeads.push(enriched)
} catch (error) {
enrichedLeads.push({
...lead,
enrichmentError: error.message,
})
}
}
// Deliver enriched leads
send.ServiceResult.deliver, {
requestId: request.id,
outputs: {
leads: enrichedLeads,
summary: {
total: request.inputs.leads.length,
enriched: enrichedLeads.filter((l) => !l.enrichmentError).length,
failed: enrichedLeads.filter((l) => l.enrichmentError).length,
averageScore: calculateAverageScore(enrichedLeads),
},
},
})
// Bill for service
const cost = request.inputs.leads.length * config.price
send.Payment.charge, {
customerId: request.customerId,
amount: cost,
description: `Lead Enrichment (${level}) - ${request.inputs.leads.length} leads`,
})
})Key Features:
- Multi-level enrichment options
- AI-powered research
- Social profile discovery
- Lead scoring
- Bulk processing
Revenue Model: $0.25-1.50 per lead Target Customers: Sales teams, marketing agencies, recruiters Processing Time: 10-30 seconds per lead
Integration Services
Example 5: Multi-Platform CRM Sync
Bidirectional CRM synchronization:
const crmSyncService = await $.Service.create({
name: 'Universal CRM Synchronizer',
type: $.ServiceType.Integration,
supportedPlatforms: ['salesforce', 'hubspot', 'pipedrive', 'zoho', 'dynamics'],
pricing: {
model: 'subscription',
tiers: [
{
name: 'starter',
price: 99,
recordLimit: 10000,
syncFrequency: 'hourly',
},
{
name: 'professional',
price: 299,
recordLimit: 100000,
syncFrequency: 'real-time',
},
{
name: 'enterprise',
price: 999,
recordLimit: Infinity,
syncFrequency: 'real-time',
customMappings: true,
},
],
},
})
// Initial sync setup
on.Integration.created, async (integration) => {
if (integration.serviceId !== crmSyncService.id) return
// Fetch all existing records from external CRM
const externalRecords = await fetchAllRecords(integration.platform, integration.credentials)
// Map and import to internal system
for (const record of externalRecords) {
const mapped = await mapToInternal(record, integration.fieldMappings)
const internal = await $.Contact.create(mapped)
// Store mapping
await db.create($.IntegrationMapping, {
integrationId: integration.id,
internalId: internal.id,
externalId: record.id,
type: 'contact',
lastSynced: new Date(),
})
}
// Mark integration as active
await db.update(integration, {
status: 'active',
lastSync: new Date(),
recordCount: externalRecords.length,
})
})
// Sync internal changes to external
on.Contact.updated, async (contact) => {
const integrations = await db.query($.Integration, {
where: {
businessId: contact.businessId,
status: 'active',
},
})
for (const integration of integrations) {
const mapping = await db.findOne($.IntegrationMapping, {
integrationId: integration.id,
internalId: contact.id,
})
if (mapping) {
// Update existing record
const externalData = await mapToExternal(contact, integration.fieldMappings)
await updateInCRM(integration.platform, integration.credentials, mapping.externalId, externalData)
await db.update(mapping, {
lastSynced: new Date(),
})
} else {
// Create new record
const externalData = await mapToExternal(contact, integration.fieldMappings)
const externalRecord = await createInCRM(integration.platform, integration.credentials, externalData)
await db.create($.IntegrationMapping, {
integrationId: integration.id,
internalId: contact.id,
externalId: externalRecord.id,
type: 'contact',
})
}
}
})
// Periodic sync from external
setInterval(async () => {
const integrations = await db.query($.Integration, {
where: { status: 'active' },
})
for (const integration of integrations) {
try {
// Fetch updates since last sync
const updates = await fetchUpdates(integration.platform, integration.credentials, integration.lastSync)
for (const update of updates) {
const mapping = await db.findOne($.IntegrationMapping, {
integrationId: integration.id,
externalId: update.id,
})
if (mapping) {
// Update internal record
const internalData = await mapToInternal(update, integration.fieldMappings)
await db.update($.Contact, {
where: { id: mapping.internalId },
data: internalData,
})
await db.update(mapping, {
lastSynced: new Date(),
})
} else {
// Create new internal record
const internalData = await mapToInternal(update, integration.fieldMappings)
const internal = await $.Contact.create(internalData)
await db.create($.IntegrationMapping, {
integrationId: integration.id,
internalId: internal.id,
externalId: update.id,
type: 'contact',
})
}
}
// Update last sync time
await db.update(integration, {
lastSync: new Date(),
})
} catch (error) {
send.Alert.create, {
severity: 'error',
title: `CRM Sync Failed: ${integration.platform}`,
error: error.message,
integrationId: integration.id,
})
}
}
}, 60000) // Every minute for real-time plansKey Features:
- Multi-platform support
- Bidirectional sync
- Custom field mappings
- Real-time or scheduled sync
- Conflict resolution
Revenue Model: $99-999/month subscription Target Customers: Businesses using multiple CRMs Value Proposition: Eliminate manual data entry, maintain data consistency
How to Use These Examples
As Learning Resources
- Start Simple: Begin with the Content Generation example
- Understand Patterns: Study the architecture and design decisions
- Experiment: Modify examples to fit your use case
- Combine Patterns: Mix and match techniques across examples
As Templates
Each example includes:
- Starter Code: Copy-paste foundation for your service
- Testing Suite: Complete test coverage examples
- Deployment Config: Production-ready configurations
- Monitoring Setup: Metrics and alerting templates
As Reference
Use examples to answer common questions:
- How do I structure a multi-stage workflow?
- What's the best way to handle errors?
- How should I price my service?
- What metrics should I track?
- How do I integrate with third-party APIs?
Example Comparison
By Implementation Time
Quick Start (1-2 weeks):
- Content Generation Service
- Data Analysis Service
Moderate (2-3 weeks):
- Automation Workflow Service
Complex (3-4 weeks):
- CRM Integration Service
By Revenue Model
Transaction-Based:
- Content Service: $29-99 per execution
- Analysis Service: $25 per execution
- Workflow Service: $1-2 per execution
Subscription-Based:
- Integration Service: $99-999 per month
By Technical Complexity
Intermediate:
- Content Generation (AI pipelines, quality checks)
- Data Analysis (data processing, reporting)
Advanced:
- Workflow Automation (state machines, integrations)
- CRM Integration (multi-platform, sync logic)
Common Patterns Across Examples
1. Input Validation
All examples demonstrate robust input validation:
// Validate inputs before execution
const validateInputs = (inputs, schema) => {
const errors = []
for (const [field, rules] of Object.entries(schema)) {
if (rules.required && !inputs[field]) {
errors.push(`${field} is required`)
}
// ... more validation
}
if (errors.length > 0) {
throw new ValidationError(errors)
}
}2. Error Recovery
Graceful error handling with retries:
// Retry with exponential backoff
const executeWithRetry = async (fn, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn()
} catch (error) {
if (i === maxRetries - 1) throw error
await delay(Math.pow(2, i) * 1000)
}
}
}3. Progress Tracking
Real-time execution progress:
// Emit progress events
const execution = {
async execute(steps) {
for (let i = 0; i < steps.length; i++) {
await this.emitProgress({
step: i + 1,
total: steps.length,
percent: ((i + 1) / steps.length) * 100,
message: steps[i].name,
})
await steps[i].execute()
}
},
}4. Cost Tracking
Monitor costs across all operations:
// Track costs per execution
const trackCosts = async (execution) => {
const costs = {
aiTokens: execution.tokensUsed * 0.00001,
storage: execution.storageUsed * 0.023,
compute: execution.duration * 0.00001,
}
costs.total = Object.values(costs).reduce((a, b) => a + b, 0)
await db.create($.CostRecord, {
executionId: execution.id,
costs,
timestamp: new Date(),
})
}Detailed Example Pages
Each example has a dedicated page with complete implementation:
Content Service Example
5,000+ lines of production code including:
- Keyword research pipeline
- Content generation with AI
- SEO optimization engine
- Image generation and optimization
- Quality assurance checks
- Delivery and formatting
Analysis Service Example
4,000+ lines of production code including:
- Data aggregation queries
- Statistical analysis algorithms
- Predictive modeling
- Report generation
- Visualization and charts
- Caching layer
Workflow Service Example
6,000+ lines of production code including:
- OCR document processing
- Multi-stage validation
- Approval routing logic
- Payment integration
- Accounting system sync
- Error recovery
Integration Service Example
7,000+ lines of production code including:
- Multi-platform adapters
- Bidirectional sync engine
- Conflict resolution
- Field mapping system
- Rate limiting
- Webhook management
Building Your Own Service
Step 1: Choose a Template
Pick the example closest to your use case:
- Content/AI work? → Start with Content Service
- Data processing? → Start with Analysis Service
- Process automation? → Start with Workflow Service
- System integration? → Start with Integration Service
Step 2: Customize
Adapt the template to your needs:
- Modify input/output schemas
- Adjust workflow stages
- Customize pricing model
- Add domain-specific logic
- Configure integrations
Step 3: Test
Use the included testing patterns:
- Unit tests for components
- Integration tests for workflows
- E2E tests for complete flows
- Performance tests for scale
- Security tests for vulnerabilities
Step 4: Deploy
Follow the deployment guides:
- Set up monitoring
- Configure alerts
- Enable logging
- Deploy to production
- Monitor and optimize
Additional Resources
More Examples Coming Soon
- Email Marketing Service - Campaign automation and analytics
- Social Media Service - Multi-platform posting and engagement
- Resume Screening Service - AI-powered candidate evaluation
- Support Ticket Service - Intelligent routing and automation
- Financial Reporting Service - Automated report generation
Example Categories
Marketing Services:
- Email campaign automation
- Social media management
- Ad optimization
- SEO analysis
Financial Services:
- Expense tracking
- Invoice generation
- Financial reporting
- Budget forecasting
Customer Service:
- Support ticket routing
- Chatbot automation
- Feedback analysis
- Knowledge base search
HR Services:
- Resume screening
- Interview scheduling
- Onboarding automation
- Performance reviews
Operations:
- Inventory management
- Supply chain optimization
- Quality assurance
- Maintenance scheduling
Next Steps
Explore the complete examples:
- Content Service → - AI content generation
- Analysis Service → - Data analysis and reporting
- Workflow Service → - Process automation
- Integration Service → - System integration
Or continue learning:
- Implementation Guides - Step-by-step guides
- API Reference - Complete API documentation
- Patterns - Advanced architectural patterns
- Best Practices - Proven guidelines