Core Concepts
Fundamental principles and architecture of Services-as-Software
Understanding the fundamental principles that make Services-as-Software different from traditional software and services.
The Services-as-Software Paradigm
Services-as-Software represents the convergence of three major trends:
- AI becomes capable of professional-grade work
- Automation reaches enterprise reliability
- Business logic becomes programmable
This convergence enables services that were traditionally human-delivered to be packaged as autonomous software.
Architecture Foundations
Service Definition Layer
Every service is defined with clear interfaces, capabilities, and constraints. Complete Service Definition Guide →
import $, { ai } from 'sdk.do'
// Define a service with complete specification
const service = await $.Service.create({
// Identity
name: 'Technical Documentation Writer',
description: 'Automated technical documentation generation',
version: '1.0.0',
// Type and category
type: $.ServiceType.ContentGeneration,
category: $.ServiceCategory.Technical,
// Capabilities
capabilities: [$.Capability.APIDocumentation, $.Capability.UserGuides, $.Capability.TutorialCreation],
// Input requirements
input: {
required: ['codebase', 'documentationType'],
optional: ['style', 'audience', 'format'],
},
// Output specification
output: {
format: ['markdown', 'html', 'pdf'],
structure: $.DocumentStructure.Hierarchical,
includes: ['code-examples', 'diagrams', 'api-reference'],
},
// Quality guarantees
sla: {
responseTime: '5 minutes',
accuracy: 0.95,
completeness: 0.9,
},
// Pricing
pricing: {
model: 'per-document',
baseRate: 50.0,
variables: {
complexity: { simple: 1.0, moderate: 1.5, complex: 2.0 },
length: { perPage: 2.0 },
},
},
})Execution Layer
Services execute through event-driven workflows:
import { on, send } from 'sdk.do'
// Listen for service requests
on.ServiceRequest.created, async (request) => {
// Validate request
const validation = await validateRequest(request, service)
if (!validation.valid) {
return send.ServiceRequest.reject, {
requestId: request.id,
reason: validation.errors,
})
}
// Execute service
try {
// Start execution
send.ServiceExecution.start, { requestId: request.id })
// Perform service work
const result = await executeService(request, service)
// Deliver results
send.ServiceResult.deliver, {
requestId: request.id,
result,
deliveryMethod: request.delivery.method,
})
// Handle billing
send.ServiceBilling.calculate, {
requestId: request.id,
serviceId: service.id,
})
} catch (error) {
send.ServiceExecution.fail, {
requestId: request.id,
error: error.message,
retryable: error.retryable,
})
}
})Composition Layer
Services can be combined to create more complex offerings:
import $, { db } from 'sdk.do'
// Define a composite service
const compositeService = await $.Service.create({
name: 'Full Content Marketing Suite',
type: $.ServiceType.Composite,
// Composed of multiple services
components: [
{
service: $.Service['SEO Keyword Research'],
stage: 1,
required: true,
},
{
service: $.Service['Blog Post Generation'],
stage: 2,
required: true,
inputs: ['keywords', 'topics'],
},
{
service: $.Service['Social Media Posts'],
stage: 3,
required: false,
inputs: ['blog-content'],
},
{
service: $.Service['Email Campaign'],
stage: 3,
required: false,
inputs: ['blog-content'],
},
],
// Composite pricing
pricing: {
model: 'bundled',
baseRate: 200.0,
discount: 0.2, // 20% off individual services
},
})
// Composite service execution
on.ServiceRequest.created, async (request) => {
if (request.serviceId !== compositeService.id) return
const results = {}
// Execute components in stages
for (const component of compositeService.components) {
// Wait for previous stage
if (component.stage > 1) {
await waitForStage(component.stage - 1)
}
// Prepare component inputs
const inputs = prepareInputs(component, results)
// Execute component service
const result = send.ServiceRequest.create, {
serviceId: component.service.id,
inputs,
parentRequest: request.id,
})
results[component.service.name] = result
}
// Deliver combined results
send.ServiceResult.deliver, {
requestId: request.id,
results,
})
})Key Design Principles
1. Autonomy
Services operate independently without human intervention:
// Autonomous decision making
on.ServiceRequest.created, async (request) => {
// Service decides how to handle request
const plan = await ai.plan({
model: 'gpt-5',
goal: request.requirements,
constraints: service.capabilities,
context: await getServiceContext(service),
})
// Execute autonomously
for (const step of plan.steps) {
const result = await executeStep(step)
// Adapt based on results
if (!result.success) {
const alternative = await ai.replan({
originalPlan: plan,
failedStep: step,
error: result.error,
})
// Continue with alternative approach
}
}
})2. Composability
Services are designed to work together:
// Services declare dependencies
const translationService = await $.Service.create({
name: 'Content Translation',
dependencies: {
optional: [$.Service['Content Quality Check']],
recommended: [$.Service['Cultural Adaptation']],
},
})
// Automatic service chaining
on.ServiceResult.delivered, async (result) => {
// Check for dependent services
const dependencies = await db.related(result.service, $.dependsOn, $.Service)
// Automatically trigger recommended services
for (const dep of dependencies) {
if (dep.automatic) {
send.ServiceRequest.create, {
serviceId: dep.id,
inputs: result.outputs,
triggeredBy: result.requestId,
})
}
}
})3. Observability
Complete visibility into service execution. Complete Monitoring Guide →
import { db } from 'sdk.do'
// Track every service execution
on.ServiceExecution.start, async (execution) => {
await db.create($.ExecutionLog, {
executionId: execution.id,
serviceId: execution.serviceId,
requestId: execution.requestId,
startTime: new Date(),
status: 'running',
})
})
// Record metrics
on.ServiceExecution.complete, async (execution) => {
await db.update($.ExecutionLog, {
where: { executionId: execution.id },
data: {
endTime: new Date(),
duration: execution.duration,
status: 'completed',
tokensUsed: execution.metrics.tokens,
cost: execution.metrics.cost,
quality: execution.metrics.quality,
},
})
// Update service analytics
await db.update(execution.service, {
totalExecutions: { increment: 1 },
averageDuration: { recalculate: 'mean' },
successRate: { recalculate: 'percentage' },
})
})4. Monetization
Every service is a revenue center. Complete Pricing & Billing Guide →
// Flexible pricing models
const pricingEngine = {
// Per-unit pricing
perUnit: (usage, rate) => usage.units * rate,
// Tiered pricing
tiered: (usage, tiers) => {
let cost = 0
let remaining = usage.units
for (const tier of tiers) {
const unitsInTier = Math.min(remaining, tier.limit - tier.start)
cost += unitsInTier * tier.rate
remaining -= unitsInTier
if (remaining <= 0) break
}
return cost
},
// Value-based pricing
valueBased: async (usage, service) => {
const value = await estimateValue(usage, service)
return value * service.pricing.valueMultiplier
},
// Dynamic pricing
dynamic: async (usage, service, context) => {
const basePrice = pricingEngine.perUnit(usage, service.pricing.baseRate)
// Adjust for demand
const demandMultiplier = await getDemandMultiplier(service)
// Adjust for user tier
const tierDiscount = context.user.tier.discount
return basePrice * demandMultiplier * (1 - tierDiscount)
},
}
// Apply pricing
on.ServiceResult.delivered, async (result) => {
const service = result.service
const usage = result.usage
const cost = await pricingEngine[service.pricing.model](usage, service, result.context)
send.Payment.charge, {
customerId: result.customerId,
amount: cost,
serviceId: service.id,
description: `${service.name} - ${result.id}`,
})
})Service Lifecycle
1. Design
Define service specification:
const spec = {
// What the service does
purpose: 'Generate SEO-optimized blog posts',
// Who it serves
targetUsers: [$.UserType.ContentMarketers, $.UserType.Bloggers],
// What it needs
requirements: {
inputs: ['topic', 'keywords', 'length'],
dependencies: [$.Service['Keyword Research']],
infrastructure: ['ai-model', 'content-storage'],
},
// What it delivers
outputs: ['blog-post', 'seo-metadata', 'performance-report'],
// How it works
workflow: ['research-topic', 'generate-outline', 'write-content', 'optimize-seo', 'quality-check', 'deliver'],
}2. Implementation
Build the service logic:
import $, { ai, db, on, send } from 'sdk.do'
const service = await $.Service.create(spec)
on.ServiceRequest.created, async (request) => {
if (request.serviceId !== service.id) return
// Research topic
const research = await ai.research({
topic: request.inputs.topic,
depth: 'comprehensive',
})
// Generate outline
const outline = await ai.generate({
model: 'gpt-5',
prompt: 'Create blog post outline',
context: { topic: request.inputs.topic, research },
})
// Write content
const content = await ai.generate({
model: 'gpt-5',
prompt: 'Write blog post',
context: { outline, keywords: request.inputs.keywords },
})
// Optimize for SEO
const optimized = await ai.optimize({
content,
keywords: request.inputs.keywords,
target: 'seo',
})
// Quality check
const quality = await ai.evaluate({
content: optimized,
criteria: ['readability', 'seo-score', 'accuracy'],
})
if (quality.score < 0.8) {
// Improve content
optimized = await ai.improve({
content: optimized,
issues: quality.issues,
})
}
// Deliver
send.ServiceResult.deliver, {
requestId: request.id,
content: optimized,
metadata: quality,
})
})3. Testing
Validate service quality:
// Test cases
const testCases = [
{
inputs: {
topic: 'AI in Healthcare',
keywords: ['ai', 'healthcare', 'diagnosis'],
length: 1500,
},
expectedOutputs: {
contentLength: { min: 1400, max: 1600 },
keywordDensity: { min: 0.01, max: 0.03 },
readabilityScore: { min: 60 },
},
},
]
// Run tests
for (const testCase of testCases) {
const result = send.ServiceRequest.create, {
serviceId: service.id,
inputs: testCase.inputs,
test: true,
})
// Validate outputs
for (const [metric, expected] of Object.entries(testCase.expectedOutputs)) {
const actual = result.metrics[metric]
if (actual < expected.min || actual > expected.max) {
throw new Error(`Test failed: ${metric} = ${actual}, expected ${expected}`)
}
}
}4. Deployment
Launch the service:
// Deploy service
await $.Service.deploy({
serviceId: service.id,
environment: 'production',
configuration: {
maxConcurrency: 100,
timeout: 300000, // 5 minutes
retryPolicy: {
maxRetries: 3,
backoff: 'exponential',
},
},
})
// Configure monitoring
await $.Monitoring.configure({
serviceId: service.id,
alerts: [
{
metric: 'errorRate',
threshold: 0.05,
action: 'notify-team',
},
{
metric: 'responseTime',
threshold: 60000, // 1 minute
action: 'scale-up',
},
],
})5. Operation
Monitor and maintain:
// Service health check
const health = await db.query($.ExecutionLog, {
serviceId: service.id,
timeRange: 'last-24-hours',
aggregate: {
totalExecutions: 'count',
successRate: 'percentage',
averageDuration: 'mean',
errorRate: 'percentage',
revenue: 'sum',
},
})
// Auto-scaling
if (health.successRate < 0.95) {
send.Service.scale, {
serviceId: service.id,
action: 'investigate',
priority: 'high',
})
}
// Performance optimization
if (health.averageDuration > 60000) {
send.Service.optimize, {
serviceId: service.id,
target: 'latency',
budget: 1000, // tokens
})
}Integration with Business-as-Code
Services-as-Software builds on Business-as-Code foundations:
import $, { db } from 'sdk.do'
// Business owns services
const business = await $.Organization.create({
name: 'ContentAI Inc',
})
// Services are business assets
await $.Organization.owns.Service({
organizationId: business.id,
serviceId: service.id,
})
// Services generate revenue
const revenue = await db.related(business, $.generates, $.Revenue, {
source: service.id,
period: 'this-month',
})
// Services have customers
const customers = await db.related(service, $.serves, $.Customer)
// Services drive growth
const growth = await db.calculate(business, {
metric: 'revenue-growth',
attributedTo: service.id,
})Next Steps
Now that you understand the core concepts:
- Quick Start Guide → - Build your first service in 5 minutes
- Explore Service Types → - See what kinds of services you can build
- Build Your First Service → - Step-by-step implementation guide
- Service Definition Guide → - Define service capabilities
- Pricing & Billing Guide → - Implement monetization
- Quality Assurance Guide → - Testing strategies
- Monitoring Guide → - Observe service health
- Learn Service Composition → - Combine services for more value
- Advanced Patterns → - Multi-service coordination and orchestration
- Complete Examples → - Production-ready service implementations