Extension SDK
Allocators
Rank candidate slots and resources to drive optimization. Used for merged visits, route optimization, dynamic pricing, and any other scoring logic.
Key points
- Allocators rank pre-validated candidate slots — they don’t accept or reject
- They run after constraint validation, so every candidate has already passed every hard constraint
- Default timeout is 30 seconds (longer than calculators or validators) since ranking is expensive
- Templates configure ranking weights; allocators apply them to produce ordered alternatives
The interface
Allocators implement IResourceAllocator. They take a list of candidate slots — already constraint-validated by the engine — and return them ordered by score:
IResourceAllocatorRanks candidate slots and resources by scoring them. Called after constraint validation, before alternatives are returned to the API caller.
Required properties
namestring— Stable identifier referenced from templatesversionstring— Semver; pinned in templates explicitly
rankScore and order the provided candidates. Return the array sorted descending by score. The engine will take the top N (configured per template).
rank(
ctx: AllocationContext,
request: AllocationRequest,
candidates: AllocationCandidate[],
): Promise<AllocationResult[]>The candidates are pre-validated — every one has passed all hard constraints. Don’t re-validate; just rank.
A complete example
The MergedVisitOptimizer from the Home Care template. It takes valid candidate slots and boosts the ones that would consolidate visits with existing same-day events:
import {
IResourceAllocator,
AllocationContext,
AllocationCandidate,
AllocationResult,
} from '@flexischeduler/extension-sdk';
export class MergedVisitOptimizer implements IResourceAllocator {
name = 'MergedVisitOptimizer';
version = '1.1.0';
async rank(
ctx: AllocationContext,
request: AllocationRequest,
candidates: AllocationCandidate[],
): Promise<AllocationResult[]> {
// Pull this participant's existing same-day events
const sameDay = await ctx.events.findByEntity({
entity_id: request.primary_entity_id,
date_range: { start: request.start_time, end: request.start_time },
});
return candidates
.map((slot) => {
let score = slot.baseScore;
// Boost slots that consolidate visits
const merge = this.findMergeOpportunity(slot, sameDay);
if (merge.feasible) {
score += 30;
}
return {
...slot,
score,
metadata: {
merge_opportunity: merge.feasible,
existing_event_ids: merge.existingIds,
travel_time_saved: merge.travelSavedMinutes,
},
};
})
.sort((a, b) => b.score - a.score);
}
private findMergeOpportunity(
slot: AllocationCandidate,
existing: ScheduledEvent[],
) {
const sameDayEvents = existing.filter((e) =>
isSameDay(e.start_time, slot.startTime),
);
if (sameDayEvents.length === 0) {
return { feasible: false, travelSavedMinutes: 0, existingIds: [] };
}
const travelSaved = sameDayEvents.length * 30; // estimate
return {
feasible: true,
travelSavedMinutes: travelSaved,
existingIds: sameDayEvents.map((e) => e.id),
};
}
}Scoring patterns
The recommended pattern is additive scoring from a base — each criterion adds or subtracts based on weights configured in your template:
// Always start from the base score, then apply your boosts and penalties
return candidates.map((slot) => {
let score = slot.baseScore;
// Each criterion adds or subtracts; weights from your template config
if (matchesProvider(slot, request)) score += weights.providerMatch;
if (hasMergeOpportunity(slot)) score += weights.mergeOpportunity;
if (offPeak(slot)) score += weights.offPeak;
if (longTravel(slot)) score -= weights.travelPenalty;
return { ...slot, score };
}).sort((a, b) => b.score - a.score);Why additive? Two reasons:
- Configurability — weights live in the template, so customers can tune ranking without code changes. Multiplicative scoring is harder to reason about in JSON config.
- Auditability — when a customer asks “why did this slot rank above that one,” you can show the score breakdown by criterion. With multiplicative or rule-based scoring, that breakdown is harder to construct.
Attach metadata to the result
Each AllocationResult can carry metadata that surfaces in the API response. Use it to explain ranking decisions to the calling system:
return {
...slot,
score,
metadata: {
merge_opportunity: true,
existing_event_ids: ['evt_a', 'evt_b'],
travel_time_saved: 45,
consolidated_activities: ['clinic_visit', 'physical_therapy'],
},
};Metadata flows back through the API and is available to your UI — useful for messages like “This slot lets us combine the visit with PT, saving ~45 minutes of travel.”
Template configuration
Allocators are wired into the template’s alternative_suggestions block. The template declares ranking criteria and weights; the allocator applies them:
{
"alternative_suggestions": {
"home_care_visit": {
"ranking_criteria": [
{ "criterion_id": "merge_opportunity", "weight": 30 },
{ "criterion_id": "route_efficiency", "weight": 25 },
{ "criterion_id": "staff_continuity", "weight": 25 },
{ "criterion_id": "time_preference", "weight": 20 }
],
"uses_extension": "MergedVisitOptimizer",
"max_suggestions": 5
}
}
}The weights are passed to your allocator through the runtime context — read ctx.config.weights rather than hardcoding values. This is what lets a customer admin tune ranking from the Config Studio without redeploying your extension.
When to use vs. validators
The line between validators and allocators is meaningful — they run at different points in the request path:
- Validators determine whether a slot can be allocated. They run first, they’re cheap, they short-circuit on hard fail. If you’re saying “no, this combination is invalid,” you want a validator.
- Allocators determine which valid slot is best. They run after validation, they’re more expensive, they take longer. If you’re saying “these are all valid; here’s the order I’d prefer them in,” you want an allocator.
Don’t reject in an allocator
rank function. Don’t. Filtering means “reject,” which is a validator’s job — and the candidate already passed every validator before you got it. If you want to reject, write a validator. If you want to deprioritize, score it low.Caveats
- Returning empty arrays is a footgun. If your allocator returns no results, the engine has no alternatives to suggest. Always rank everything, even if you score some candidates very low.
- Score consistency matters. Different allocators in the same template should use comparable score scales (typically 0-100). Mixing scales makes the final ranking unstable.
- Be careful with external API calls. Allocators run on potentially many candidates — N candidates × M API calls per candidate = a lot. Batch where possible; cache aggressively.
- Sort descending. Convention is highest score first. The engine takes the top N from your sorted list — if you sort wrong, you give the worst candidates back.