Feature Flags
O Building Block Feature Flags fornece funcionalidades para gerenciamento de feature flags, segmentos de usuários e regras de targeting na Catalisa Platform.
Visão Geral
O Feature Flags é um módulo tenant-scoped, ou seja, requer um token com organizationId. Ele é responsável por:
- Gerenciamento de Feature Flags (criação, ativação, desativação)
- Gerenciamento de Segmentos de usuários com regras simples ou DMN
- Targeting Rules para controle granular de rollout
- Overrides para usuários específicos
- Avaliação de flags em tempo real com cache inteligente
Base URL
https://api.catalisa.io/feature-flags
Recursos
| Recurso | Descrição |
|---|---|
| Flags | CRUD de feature flags |
| Segmentos | Segmentos de usuários |
| Targeting Rules | Regras de targeting |
| Overrides | Overrides por usuário |
| Avaliação | Endpoints de avaliação |
Permissões
| Permissão | Descrição |
|---|---|
FEATURE_FLAGS_CREATE | Criar feature flags |
FEATURE_FLAGS_READ | Listar e visualizar feature flags |
FEATURE_FLAGS_UPDATE | Atualizar feature flags |
FEATURE_FLAGS_DELETE | Excluir feature flags |
FEATURE_FLAGS_TOGGLE | Ativar/desativar feature flags |
FEATURE_FLAGS_EVALUATE | Avaliar feature flags |
SEGMENTS_CREATE | Criar segmentos |
SEGMENTS_READ | Listar e visualizar segmentos |
SEGMENTS_UPDATE | Atualizar segmentos |
SEGMENTS_DELETE | Excluir segmentos |
Exemplo Rápido
Fluxo básico para criar uma feature flag com targeting:
// 1. Criar uma Feature Flag
const flagResponse = await fetch('https://api.catalisa.io/feature-flags/api/v1/feature-flags', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'new-checkout-flow',
name: 'New Checkout Flow',
description: 'Novo fluxo de checkout com pagamento PIX',
variations: [
{ key: 'on', value: true },
{ key: 'off', value: false },
],
defaultVariation: 'off',
}),
});
const flag = await flagResponse.json();
// 2. Criar um Segmento para usuários premium
const segmentResponse = await fetch('https://api.catalisa.io/feature-flags/api/v1/segments', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'premium-users',
name: 'Premium Users',
ruleType: 'SIMPLE',
ruleContent: JSON.stringify({
operator: 'AND',
conditions: [
{ attribute: 'plan', operator: 'eq', value: 'premium' },
],
}),
}),
});
const segment = await segmentResponse.json();
// 3. Criar uma Targeting Rule
await fetch(`https://api.catalisa.io/feature-flags/api/v1/feature-flags/${flag.data.id}/targeting-rules`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'Premium users rollout',
variationKey: 'on',
rolloutPercentage: 50,
segmentIds: [segment.data.id],
}),
});
// 4. Ativar a flag
await fetch(`https://api.catalisa.io/feature-flags/api/v1/feature-flags/${flag.data.id}/enable`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
// 5. Avaliar a flag para um usuário
const evalResponse = await fetch('https://api.catalisa.io/feature-flags/api/v1/feature-flags/evaluate/new-checkout-flow', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
context: {
userId: 'user-123',
attributes: {
plan: 'premium',
},
},
}),
});
const { data } = await evalResponse.json();
console.log(`Flag value: ${data.value}`);
console.log(`Reason: ${data.reason}`);
Arquitetura
┌─────────────────────────────────────────────────────────────────────┐
│ Feature Flags │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Flags │ │ Segments │ │ Targeting │ │
│ │ │ │ │ │ Rules │ │
│ │ - key │ │ - SIMPLE │ │ │ │
│ │ - status │ │ - DMN │ │ - priority │ │
│ │ - variations│ │ - conditions│ │ - rollout % │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ └───────────────────┼───────────────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ Evaluation │ │
│ │ Service │ │
│ └────────┬────────┘ │
│ │ │
│ ┌───────────────────┼───────────────────┐ │
│ │ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ │
│ │ Override │ │ Cache │ │ Decision │ │
│ │ Check │ │ (Redis) │ │ Engine │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Conceitos Importantes
Variations
Variations são os possíveis valores que uma feature flag pode retornar:
| Campo | Descrição |
|---|---|
key | Identificador único da variação (ex: on, off, variant-a) |
value | Valor retornado (boolean, string, number, object, array) |
Status da Flag
| Status | Descrição |
|---|---|
ENABLED | Flag ativa - avaliação considera targeting rules |
DISABLED | Flag desativada - retorna sempre default variation |
Tipos de Segmento
| Tipo | Descrição |
|---|---|
SIMPLE | Regras baseadas em condições simples (atributo, operador, valor) |
DMN | Regras complexas usando tabelas de decisão DMN |
Operadores de Condição (SIMPLE)
| Operador | Descrição |
|---|---|
eq | Igual |
neq | Diferente |
gt | Maior que |
gte | Maior ou igual |
lt | Menor que |
lte | Menor ou igual |
in | Esta na lista |
notIn | Não esta na lista |
contains | Contém (string) |
startsWith | Começa com (string) |
endsWith | Termina com (string) |
Lógica de Avaliação
A avaliação de uma flag segue esta ordem:
- Flag desativada? → Retorna
defaultVariation(reason:DISABLED) - Override para o usuário? → Retorna variação do override (reason:
OVERRIDE) - Targeting rule match? → Aplica rollout percentage (reason:
RULE_MATCH) - Nenhum match? → Retorna
defaultVariation(reason:DEFAULT)
Rollout Percentual
O rollout percentual permite liberar uma variação gradualmente:
- Baseado em hash consistente do
userId - Mesmo usuário sempre recebe mesmo resultado
- Incrementar de 10% para 50% inclui usuários anteriores
Cache
- Resultados de avaliação são cacheados por 5 minutos
- Membership de segmentos cacheados por 15 minutos
- Cache invalidado automaticamente em updates