Nel contesto di sistemi di messaging, API, protocolli di rete, code di messaggi (message queues), event streaming, il payload è il contenuto informativo effettivo trasportato dal messaggio, distinto da header/metadata/routing info.
Struttura generica messaggio
MESSAGE
├── HEADER / METADATA (routing, identificazione, controllo)
│ ├── Message ID (UUID)
│ ├── Timestamp (ISO 8601 / Unix epoch)
│ ├── Source / Sender ID
│ ├── Destination / Topic / Queue / Exchange / Channel
│ ├── Message Type / Schema Version
│ ├── Correlation ID / Conversation ID
│ ├── Priority / TTL / Expiration
│ ├── Security: Signature, Encryption Key ID, MAC
│ └── Custom Headers (tenant, trace-id, feature-flags)
└── PAYLOAD (BODY) — IL CONTENUTO CHE CONTA
├── Format: JSON, XML, Protobuf, Avro, MessagePack, CBOR, Plain Text, Binary
├── Schema: definito da contratto (OpenAPI, AsyncAPI, JSON Schema, Protobuf .proto)
└── Data: oggetti, eventi, comandi, documenti, metriche, log, file (chunked)
Tipi comuni di payload
| Tipo | Formato tipico | Esempi |
| Testo / Comando | Plain text, JSON, XML | Chat message, CLI command, config update, SQL query |
| Evento / Notifica | JSON, CloudEvents, Protobuf | OrderCreated, UserSignedUp, SensorThresholdExceeded, LogEntry |
| Dato / Documento | JSON, XML, CSV, Parquet, Binary (file) | Report PDF, immagine, dataset, backup chunk, firmware blob |
| RPC / Request-Response | JSON-RPC, gRPC (Protobuf), Thrift, MessagePack | GetUserProfile(id), ProcessPayment(amount, currency), InvokeLambda |
| Streaming / Telemetria | Protobuf, Avro, MessagePack, CSV | Metrics (Prometheus), Traces (OTLP), Logs (JSON), Time-series |
Esempi concreti
1. JSON (ubiquo, human-readable, schema-less ma validabile)
{
"event": "OrderPlaced",
"timestamp": "2024-01-15T10:30:00.123Z",
"payload": {
"orderId": "ORD-20240115-0042",
"customerId": "CUST-789",
"items": [
{"sku": "LAPTOP-X1", "qty": 1, "unitPrice": 1299.00},
{"sku": "MOUSE-ERGO", "qty": 2, "unitPrice": 49.90}
],
"totals": {"subtotal": 1398.80, "tax": 279.76, "shipping": 0, "grandTotal": 1678.56},
"payment": {"method": "card", "last4": "4242", "authCode": "AUTH_1A2B3C"}
}
}
2. Protobuf (binario, veloce, schema forte, versioning)
// order.proto
syntax = "proto3";
message OrderPlaced {
string order_id = 1;
string customer_id = 2;
repeated OrderItem items = 3;
Money grand_total = 4;
PaymentInfo payment = 5;
int64 timestamp_ms = 6;
}
message OrderItem { string sku = 1; int32 qty = 2; Money unit_price = 3; }
message Money { int64 micros = 1; string currency = 2; }
message PaymentInfo { string method = 1; string last4 = 2; string auth_code = 3; }
3. Binary / File (chunked per messaggi grandi)
Payload = chunk bytes + metadata (chunkIndex, totalChunks, fileHash, mimeType). Usa object storage (S3, Azure Blob) + messaggio con reference (presigned URL) per file > 1-10 MB.
Sicurezza del payload
- Crittografia in transito: TLS 1.2/1.3 (mutual TLS per zero-trust).
- Crittografia a riposo / end-to-end: AES-256-GCM / ChaCha20-Poly1305 per payload sensibili (PII, finanziari, sanitari). Key management: KMS / Vault / HSM.
- Firma / Integrità: HMAC-SHA256 / Ed25519 su payload + header critici → previene tampering.
- Schema validation: lato producer e consumer → evita injection, parsing errors, schema evolution sicura (backward/forward compatibility rules).
- Sanitizzazione: no eval/deserializzazione non sicura (Java deserialization, pickle, YAML unsafe_load). Usa parser safe (JSON.parse, protobuf parser, simdjson).
- Dimensione limiti: max payload size per topic/queue → previene DoS / OOM.
Best practice design
- Contratto esplicito (schema registry): Confluent Schema Registry / Apicurio / custom — versiona, valida, evolve.
- Single responsibility: un messaggio = un evento/comando/documento logico.
- Idempotency key: nel payload o header → consumer può deduplicare.
- Timestamp source-of-truth: producer timestamp (non broker/consumer).
- Compressione: gzip/zstd/snappy su payload > 1 KB (header `Content-Encoding`).
- Osservabilità: log payload (sampled, redacted PII) + metriche size/latency/errori per schema version.
Il payload è il valore di business del sistema di messaging. Header lo instradano; payload lo realizza. Progetta schema, sicurezza, evoluzione con la stessa cura dell'API pubblica.