Schéma Technique
Flux de Données
La solution de cashback nouvelle génération
INTRODUCTION ET VUE D'ENSEMBLE
1.1 Objectif du Document
Ce document décrit en détail les flux de données circulant au sein de l'écosystème REWAPP. Il présente les interactions entre les différents services, les protocoles de communication utilisés, et les mécanismes de sécurité appliqués à chaque flux.
ARCHITECTURE HYBRIDE
L'architecture REWAPP repose sur une combinaison de flux synchrones (REST API) pour les opérations nécessitant une réponse immédiate, et de flux asynchrones (Event-Driven via Bull Queue) pour les traitements différés et les notifications.
1.2 Composants Principaux
L'écosystème REWAPP comprend les composants suivants qui échangent des données :
Composants de l'Écosystème
| Catégorie | Composants |
|---|---|
| Applications Clientes | App Mobile (Angular + Ionic), Site Vitrine (Next.js), Dashboard Admin (React), Dashboard Partenaire (React PWA) |
| API Gateway | Point d'entrée unique (Kong / Traefik) |
| Microservices Backend | Auth Service, User Service, Transaction Service, Points Service, QR Code Service, Merchant Service, Banking Service, Notification Service, Admin Service |
| Bases de Données | PostgreSQL (données persistantes), Redis (cache, sessions, queues) |
| Services Externes | Budget Insight (bancaire), Firebase Cloud Messaging, SendGrid, Twilio, Google Analytics |
1.3 Principes de Conception des Flux
-
API-First Toute communication passe par des APIs REST standardisées (OpenAPI 3.0)
-
Stateless Aucune session serveur, authentification via JWT pour scalabilité horizontale
-
Event-Driven Communication asynchrone entre services via Bull Queue (Redis)
-
Security by Design Chiffrement TLS 1.3, signature des données sensibles
-
Idempotence Les opérations critiques sont idempotentes pour éviter les doublons
ARCHITECTURE DES FLUX DE DONNÉES
2.1 Vue Globale de l'Architecture
Architecture en Couches
| Couche | Composants | Flux Entrants | Flux Sortants |
|---|---|---|---|
| Présentation | App Mobile, Site Vitrine, Dashboards | Interactions utilisateur | Requêtes HTTPS vers API Gateway |
| API Gateway | Kong / Traefik | Requêtes HTTPS authentifiées | Routage vers microservices |
| Services Métier | 9 Microservices NestJS | Requêtes REST internes, Events | Réponses JSON, Events Bull Queue |
| Données | PostgreSQL, Redis | Requêtes SQL, Commandes Redis | Résultats requêtes, Données cache |
| Externe | Budget Insight, FCM, SendGrid | Webhooks, Callbacks | Requêtes API tierces |
2.2 Patterns de Communication
Patterns Utilisés
| Pattern | Usage | Protocole | Exemple |
|---|---|---|---|
| Request-Response | Opérations synchrones | REST HTTPS |
Consultation solde de points |
| Event-Driven | Opérations asynchrones | Bull Queue (Redis) |
Notification push après transaction |
| Webhook | Intégrations externes | HTTPS POST |
Réception transaction bancaire |
| Pub/Sub | Temps réel | WebSocket |
Mise à jour statut QR code |
2.3 Formats de Données
Toutes les données échangées utilisent le format JSON avec les conventions suivantes :
- Nommage : camelCase pour les propriétés
- Dates : Format ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ)
- Identifiants : UUID v4 non séquentiels
- Montants : Entiers (cents pour euros, unités pour points)
- Encodage : UTF-8
FLUX SYNCHRONES (REST API)
3.1 Flux Client vers API Gateway
Les applications clientes communiquent avec l'API Gateway via HTTPS (TLS 1.3). Chaque requête authentifiée inclut un token JWT dans le header Authorization.
Flux Clients → API Gateway
| Source | Destination | Protocole | Authentification | Contenu |
|---|---|---|---|---|
| App Mobile | API Gateway | HTTPS/REST |
JWT Bearer Token | Requêtes utilisateur |
| Site Vitrine | API Gateway | HTTPS/REST |
Optionnel (pages publiques) | Inscription, consultation partenaires |
| Dashboard Admin | API Gateway | HTTPS/REST |
JWT + 2FA obligatoire | Opérations administration |
| Dashboard Partenaire | API Gateway | HTTPS/REST |
JWT Bearer Token | Scan QR, statistiques |
3.2 Flux API Gateway vers Microservices
L'API Gateway route les requêtes vers le microservice approprié en fonction du path URL.
Routage API Gateway
| Path URL | Service Cible | Description | Timeout |
|---|---|---|---|
/api/v1/auth/* |
Auth Service | Authentification, tokens | 5s |
/api/v1/users/* |
User Service | Profil utilisateur | 5s |
/api/v1/transactions/* |
Transaction Service | Historique achats | 5s |
/api/v1/points/* |
Points Service | Solde, historique points | 5s |
/api/v1/qr-codes/* |
QR Code Service | Génération, validation QR | 5s |
/api/v1/partners/* |
Merchant Service | Liste partenaires (public) | 5s |
/api/v1/merchant/* |
Merchant Service | Dashboard partenaire | 5s |
/api/v1/banking/* |
Banking Service | Cartes, virements | 10s |
/api/v1/notifications/* |
Notification Service | Centre notifications | 5s |
/api/v1/admin/* |
Admin Service | Administration | 5s |
3.3 Flux Inter-Services Synchrones
Certains microservices communiquent entre eux de manière synchrone pour des opérations nécessitant une réponse immédiate.
Communications Inter-Services
| Service Source | Service Cible | Opération | Données Échangées |
|---|---|---|---|
| Transaction Service | Points Service | Crédit points | userId, amount, transactionId |
| QR Code Service | Points Service | Blocage/Déblocage points | userId, amount, qrCodeId |
| Points Service | User Service | Vérification utilisateur | userId |
| Banking Service | Points Service | Débit pour virement | userId, amount, withdrawalId |
| Merchant Service | Points Service | Débit QR scan | userId, merchantId, amount |
| Admin Service | User Service | Suspension compte | userId, reason |
| Admin Service | Merchant Service | Validation partenaire | merchantId, status |
FLUX ASYNCHRONES (EVENT-DRIVEN)
4.1 Architecture Bull Queue
Les flux asynchrones utilisent Bull Queue (basé sur Redis) pour le traitement en arrière-plan et la communication inter-services découplée.
Queues Bull
| Queue | Priorité | Description | Consumers |
|---|---|---|---|
transactions |
High | Traitement transactions bancaires | Transaction Service |
points |
High | Calcul et crédit des points | Points Service |
withdrawals |
High | Traitement virements SEPA | Banking Service |
notifications |
Medium | Envoi push/email/SMS | Notification Service |
analytics |
Low | Tracking et métriques | Analytics Service |
tier-calculation |
Low | Recalcul quotidien paliers | Points Service |
4.2 Événements Principaux
Catalogue des Événements
| Événement | Producteur | Consommateur(s) | Payload |
|---|---|---|---|
user.registered |
Auth Service | Notification Service, Analytics | userId, email, timestamp |
card.linked |
Banking Service | Notification Service | userId, cardLastFour, timestamp |
transaction.detected |
Transaction Service | Points Service | userId, merchantId, amount, transactionId |
points.credited |
Points Service | Notification Service | userId, amount, balance, transactionId |
qr_code.generated |
QR Code Service | Points Service | userId, qrCodeId, amount, expiresAt |
qr_code.scanned |
Merchant Service | Points Service, Notification Service | userId, merchantId, qrCodeId, amount |
qr_code.expired |
QR Code Service | Points Service | userId, qrCodeId, amount |
withdrawal.requested |
Banking Service | Admin Service | userId, amount, iban, withdrawalId |
withdrawal.completed |
Banking Service | Notification Service | userId, amount, withdrawalId |
tier.upgraded |
Points Service | Notification Service | userId, merchantId, newTier, previousTier |
merchant.validated |
Admin Service | Notification Service, Merchant Service | merchantId, status |
4.3 Configuration des Jobs
Paramètres Bull Queue
| Paramètre | Valeur | Description |
|---|---|---|
Attempts |
3 | Nombre de tentatives en cas d'échec |
Backoff Type |
Exponential | Type de délai entre tentatives |
Backoff Delay |
1000ms | Délai initial (1s, 2s, 4s) |
Remove On Complete |
true | Suppression job après succès |
Remove On Fail |
false | Conservation pour analyse |
TTL |
24h | Durée de vie maximale du job |
FLUX DE DONNÉES PAR DOMAINE FONCTIONNEL
5.1 Flux d'Inscription Utilisateur
Soumission formulaire
App Mobile → API Gateway : email, password, firstName, lastName
Validation données
API Gateway → Auth Service : Données validées
Création compte
Auth Service → PostgreSQL : User entity → Table users
Génération tokens
Auth Service : JWT access + refresh → Redis (refresh)
Event user.registered
Auth Service → Bull Queue : userId, email → Queue notifications
Email bienvenue
Notification Service → SendGrid : Template + données
Réponse client
Auth Service → App Mobile : tokens, user profile
5.2 Flux de Liaison Carte Bancaire (Card Linking)
Initiation liaison
App Mobile → Banking Service : userId
Redirection OAuth
Banking Service → Budget Insight : redirect_uri, scope
Authentification banque
Utilisateur → Banque : credentials
Callback OAuth
Budget Insight → Banking Service : authorization_code
Échange token
Banking Service → Budget Insight : code → access_token
Récupération carte
Banking Service → Budget Insight : access_token
Stockage token
Banking Service → PostgreSQL : card_token (tokenisé) → Table cards
Event card.linked
Banking Service → Bull Queue : userId, cardLastFour → Queue notifications
Notification
Notification Service → FCM : Push notification
5.3 Flux de Détection Transaction et Crédit Points
FLUX CRITIQUE
Ce flux est au cœur du système de cashback. La détection automatique des transactions et le crédit des points doit être fiable et performant.
Étapes du Flux Transaction → Points
| Étape | Flux | Données | Stockage |
|---|---|---|---|
| 1 | Achat client | Client → Commerçant partenaire : Paiement carte | - |
| 2 | Webhook transaction | Budget Insight → Banking Service : transaction details | - |
| 3 | Validation webhook | Banking Service : Signature HMAC | - |
| 4 | Matching partenaire | Transaction Service : merchantName, MCC | Table merchants |
| 5 | Calcul cashback | amount × taux × (1 + bonus_palier) | - |
| 6 | Stockage transaction | Transaction Service → PostgreSQL : Transaction entity | Table transactions |
| 7 | Event transaction.detected | Transaction Service → Bull Queue : transactionId, userId, points | Queue points |
| 8 | Crédit points | Points Service → PostgreSQL : Points ledger entry | Table points_ledger |
| 9 | Event points.credited | Points Service → Bull Queue : userId, amount, balance | Queue notifications |
| 10 | Notification push | Notification Service → FCM : "+X points chez [Partenaire]!" | - |
5.4 Flux de Génération QR Code
QR CODE SÉCURISÉ
QR Code valide 60 secondes, usage UNIQUE, signature HMAC-SHA256
Étapes Génération QR
| Étape | Flux | Données | Stockage |
|---|---|---|---|
| 1 | Demande génération | App Mobile → QR Code Service : userId, pointsAmount | - |
| 2 | Vérification solde | QR Code Service → Points Service : userId | - |
| 3 | Blocage points | Points Service → Redis : userId, amount | locked:{userId}:{qrId} |
| 4 | Génération QR | QR Code Service : qrCodeId, signature HMAC-SHA256 | - |
| 5 | Stockage QR | QR Code Service → Redis : QR code data | qr:{qrCodeId} (TTL 60s) |
| 6 | Réponse client | QR Code Service → App Mobile : qrCodeImage, expiresAt | - |
| 7 | Timer expiration | QR Code Service (60s) | - |
| 8 | Si expiré : déblocage | Points Service → Redis : Suppression lock | - |
5.5 Flux de Scan QR Code et Débit Points
Étapes Scan et Validation QR
| Étape | Flux | Données | Stockage |
|---|---|---|---|
| 1 | Scan QR | Dashboard Partenaire → QR Code Service : qrCodeData | - |
| 2 | Validation QR | QR Code Service → Redis : qrCodeId | qr:{qrCodeId} |
| 3 | Vérification signature | QR Code Service : HMAC-SHA256 validation | - |
| 4 | Vérification expiration | QR Code Service : timestamp < now + 60s | - |
| 5 | Vérification usage unique | QR Code Service → Redis : used flag | - |
| 6 | Marquage utilisé | QR Code Service → Redis : Set used flag | qr:{qrCodeId}:used |
| 7 | Débit points | Points Service → PostgreSQL : Points ledger entry (débit) | Table points_ledger |
| 8 | Déblocage points | Points Service → Redis : Remove lock | locked:{userId}:{qrId} |
| 9 | Event qr_code.scanned | QR Code Service → Bull Queue : userId, merchantId, amount | Queue notifications |
| 10 | Notification client | Notification Service → FCM : "Paiement validé chez [Partenaire]" | - |
| 11 | Notification partenaire | WebSocket : Confirmation scan → Dashboard Partenaire | - |
5.6 Flux de Demande de Virement Bancaire
Étapes Virement SEPA
| Étape | Flux | Données | Stockage |
|---|---|---|---|
| 1 | Demande virement | App Mobile → Banking Service : userId, amount (min 100 pts), iban | - |
| 2 | Vérification solde | Banking Service → Points Service : userId | - |
| 3 | Vérification seuil | Banking Service : amount >= 100 points | - |
| 4 | Conversion euros | Banking Service : points × 0.095 (ratio -5%) | - |
| 5 | Blocage points | Points Service → PostgreSQL : Status BLOCKED | Table points_ledger |
| 6 | Création demande | Banking Service → PostgreSQL : Withdrawal entity | Table withdrawals |
| 7 | Event withdrawal.requested | Banking Service → Bull Queue : withdrawalId, amount | Queue withdrawals |
| 8 | Traitement batch | Banking Service → Provider SEPA : Initiation virement | - |
| 9 | Webhook confirmation | Provider SEPA → Banking Service : virement effectué | - |
| 10 | Débit définitif | Points Service → PostgreSQL : Points débités | Table points_ledger |
| 11 | MAJ statut | Banking Service → PostgreSQL : Status COMPLETED | Table withdrawals |
| 12 | Notification | Notification Service → FCM : "Virement de X€ effectué" | - |
DIAGRAMMES DE FLUX DE DONNÉES
6.1 Diagramme Global - Architecture des Flux
6.2 Diagramme de Séquence - Flux Transaction Complète
6.3 Diagramme de Séquence - Flux QR Code Complet
6.4 Diagramme de Flux de Données - Vue DFD Niveau 1
SÉCURITÉ DES FLUX DE DONNÉES
7.1 Chiffrement des Données en Transit
Protocoles de Chiffrement
| Flux | Protocole | Chiffrement | Certificat |
|---|---|---|---|
| Client → API Gateway | HTTPS |
TLS 1.3 | Let's Encrypt / ACM |
| API Gateway → Services | HTTPS |
TLS 1.2+ | Certificats internes |
| Services → PostgreSQL | SSL |
TLS 1.2 | PostgreSQL Certificate |
| Services → Redis | TLS |
TLS 1.2 | Redis Certificate |
| Services → Externes | HTTPS |
TLS 1.3 | Certificats partenaires |
7.2 Authentification des Flux
Méthodes d'Authentification
| Flux | Méthode | Durée Validité | Renouvellement |
|---|---|---|---|
| Client → API | JWT Bearer Token (RS256) |
15 minutes | Refresh token (7 jours) |
| Webhooks entrants | Signature HMAC-SHA256 |
Par requête | - |
| Inter-services | Service Token JWT |
1 heure | Automatique |
| Admin Dashboard | JWT + 2FA TOTP |
15 minutes | Après validation 2FA |
7.3 Validation des Données
Types de Validation
| Type de Validation | Emplacement | Outil | Exemple |
|---|---|---|---|
| Schéma JSON | API Gateway | JSON Schema |
Validation structure requête |
| Règles métier | Services | class-validator |
Montant minimum 10 points |
| Sanitization | Services | class-transformer |
Nettoyage HTML/SQL |
| Intégrité | Services | HMAC-SHA256 |
Signature QR code |
7.4 Protection des Données Sensibles
Classification et Protection
| Donnée | Classification | Protection | Stockage |
|---|---|---|---|
| Mot de passe | Critique | Hashage bcrypt (10 rounds) | PostgreSQL |
| Carte bancaire | Critique | Tokenisation PCI DSS | Chez Budget Insight |
| IBAN | Sensible | Chiffrement AES-256 | PostgreSQL |
| Personnel | Pseudonymisation logs | PostgreSQL | |
| Refresh token | Sensible | Hashage SHA-256 | Redis |
GESTION DES ERREURS ET RETRY
8.1 Stratégie de Retry
Configuration Retry par Type de Flux
| Type de Flux | Retry | Délai | Max Tentatives | Action Échec |
|---|---|---|---|---|
| REST synchrone | Oui | Exponential backoff | 3 | Réponse erreur client |
| Bull Queue | Oui | 1s, 2s, 4s | 3 | Dead Letter Queue |
| Webhook sortant | Oui | 5s, 30s, 300s | 5 | Log + alerte |
| WebSocket | Reconnexion auto | 1s, 2s, 5s | 10 | Fallback polling |
8.2 Dead Letter Queue (DLQ)
Les messages en échec après toutes les tentatives sont placés dans une Dead Letter Queue pour analyse :
- Stockage : Queue Redis dédiée (
dlq:{queue_name}) - Rétention : 7 jours
- Alerting : Notification Slack si DLQ > 100 messages
- Replay : Possibilité de rejouer manuellement les messages
8.3 Circuit Breaker
Configuration Circuit Breaker
| Service | Seuil Ouverture | Timeout Demi-Ouvert | Actions |
|---|---|---|---|
| Budget Insight | 50% erreurs sur 30s | 30 secondes | Fallback mode dégradé |
| SendGrid | 30% erreurs sur 60s | 60 secondes | Fallback vers Brevo |
| Firebase FCM | 20% erreurs sur 30s | 30 secondes | Mise en queue différée |
8.4 Idempotence
Toutes les opérations critiques sont idempotentes grâce à des identifiants uniques :
- Transactions : transactionId unique (UUID fourni par le webhook)
- Points : Clé composite (userId, transactionId, type)
- QR Codes : qrCodeId unique avec flag "used" atomique
- Virements : withdrawalId avec vérification statut préalable
MONITORING DES FLUX
9.1 Métriques de Flux
Métriques Surveillées
| Métrique | Description | Seuil Alerte | Outil |
|---|---|---|---|
Latence API P95 |
Temps de réponse 95e percentile | > 300ms | Prometheus/Grafana |
Throughput |
Requêtes par seconde | < 100 rps (production) | Prometheus |
Error Rate |
Taux d'erreurs 5xx | > 1% | Sentry |
Queue Depth |
Nombre de jobs en attente | > 1000 | Bull Board |
Queue Latency |
Temps de traitement moyen | > 5s | Prometheus |
Webhook Success |
Taux de succès webhooks | < 95% | Prometheus/Grafana |
9.2 Tracing Distribué
Chaque requête est tracée à travers tous les services avec un identifiant unique :
- Request ID : UUID généré par l'API Gateway
- Trace ID : Propagé dans les headers (X-Request-ID)
- Span ID : Identifiant de chaque opération
- Corrélation : Logs enrichis avec requestId pour suivi end-to-end
9.3 Logs des Flux
Niveaux de Logs
| Niveau | Événements | Rétention | Destination |
|---|---|---|---|
| INFO | Requêtes entrantes/sortantes, succès | 30 jours | Loki/CapRover Logs |
| WARN | Retries, timeouts, dégradations | 90 jours | Loki/CapRover Logs |
| ERROR | Échecs, exceptions, erreurs métier | 1 an | Prometheus/Grafana + Sentry |
| DEBUG | Détails techniques (dev/staging uniquement) | 7 jours | Loki/CapRover Logs |
9.4 Dashboards de Monitoring
Dashboards Disponibles
| Dashboard | Audience | Métriques Clés |
|---|---|---|
| Flux API | Dev/Ops | Latence, throughput, erreurs par endpoint |
| Flux Events | Dev/Ops | Queue depth, processing time, DLQ count |
| Flux Bancaires | Business | Transactions détectées, taux matching, webhooks |
| Flux Notifications | Marketing | Delivery rate, open rate, bounce rate |
CONCLUSION
10.1 Récapitulatif des Flux
L'architecture de flux de données REWAPP repose sur une combinaison équilibrée de communications synchrones et asynchrones :
- Flux synchrones : Opérations utilisateur nécessitant une réponse immédiate (< 200ms)
- Flux asynchrones : Traitements en arrière-plan, notifications, calculs différés
- Webhooks : Intégration avec les partenaires externes (solution bancaire)
- WebSocket : Communications temps réel (scan QR, notifications dashboard)
10.2 Points Clés de l'Architecture
-
Découplage Les services communiquent via API et events, permettant une évolution indépendante
-
Résilience Retry automatique, circuit breakers, dead letter queues
-
Scalabilité Architecture stateless, queues distribuées, auto-scaling
-
Sécurité Chiffrement bout-en-bout, authentification JWT, signatures HMAC
-
Observabilité Tracing distribué, métriques temps réel, alerting proactif
10.3 Références Complémentaires
DOCUMENTS CONNEXES
- Document 4.1 - Architecture Technique Globale
- Document 4.3 - Architecture Backend API
- Document 5.2 - Diagrammes de Séquence
- Document 5.3 - Schéma Technique - Flux Bancaire
- Document 5.5 - Schéma d'Infrastructure Cloud
- Document 6.1 - Document de Sécurité
- Document 7.2 - Spécifications Webhooks