I will give you my description of the Python service I am making right now, and then I will give you a documentation that I've made for my another service that I've made. I want to you create similar documentation for my new service based on the description.
Description:
Diamonds Service.
The Diamonds Service allows users to collect diamonds (points), manage streaks, and calculate referral bonuses. It ensures the proper tracking of user interactions, reward calculations, and asynchronous updates via WebSocket connections for real-time feedback. For authentication it just uses JWT access token + refresh token, that we claim using my other service - Auth service, so we just share jwt secret and don't need to worry about authentication as long as JWT is properly signed and not expired, all the data needed for diamond service to work with user - is auth_uer_uuid which is stored inside the JWT payload. The diamonds service itself is a mono repository with CQRS architecture application that consists 3 main parts:
diamonds-domain - it is a common part of the service, used as a library in other 2 parts of the service, it contains a common code like: classes to work with Postgers database, models, Redis manager to handle work with Redis, pulsar manager to handle work with Apache Pulsar and some common configs and constants.
diamonds-service - read-only service, written with FastAPI. It handles all the Client-Service communication, read data from DB and Redis cache, make requests validations and send Pulsar messages, that will be consumed by worker. It also handles the WebSocket connection with Client and subscribed to Pulsar updates topic, messages from this topic are propagated to Client through this WS connection giving us an ability to make seamless real time updates, while the app maintain it's CQRS nature and make all the updates asynchronously.
diamonds-worker - it is read-write service, written in pure python. Worker itself is not exposed to the network, it listens to Pulsar messages from Diamond Service and handle those messages as commands, making updates to DB and Redis cache. To ensure eventual consistency and idempotency of those commands Worker uses event driven approach, and stores all the events into event log with all required data to prevent false claims, double claims, malicious updates (like idempotency key for each command, command execution timestamp, etc.) It also uses Write Through strategy of updating Redis cache, therefore Diamond Service could rely on cache (if it exist at the moment of the request) as the source of truth, which reduce the number of DB calls. After updates has been made (in both DB and cache) Worker send updated profile data to updates topic inPulsar, which consumed by Diamond Service and those updates sent to Client in real time. To prevent concurrency Worker subscribed to commands topic which is partitioned by user unique uuid, which make all the commands for the same user being executed sequecially. It gives us ability to use DB updates without exclusive locks.
Assistant
All the part of this app are using similar layered approach as my other services(for example Auth service, I'll share its documentations as an example below.)
Example documentation. This documentation was made for my other service - Auth service. It uses similar tech stack and a lot of similat approached with layers, repositories, services, managers and usecases. Here is the doc:
Solution Architecture Overview
This service is designed to authenticate users across the entire ecosystem, ensuring a seamless and secure entry. It eliminates traditional registration by adopting a sign-in scheme and offers various login methods:
Authentication Methods
1. OTP (One-Time Password)
Process: Users enter their email and receive a numeric 6-digits temporary password.
Security Measures: After five incorrect password attempts, the user gets temporarily banned for 24 hours. Similarly, if there are five consecutive attempts to resend the password to the same email, the user faces a 24-hour ban. These measures effectively combat brute force and DDoS attacks.
2. Crypto Wallet Authentication
Approach: Utilizes the EIP-4361 format for authorization. All addresses are stored in EIP-55 format.
Security Measures: Beside signature verification, message itself validates against regular expression due to format EIP-4361. Also message data is partially generated on the backend side with random nonce, session key(in the form of UUID) and issue/expiration dates. All this data, as well as the domain and the request uri is validated, therefore we could be sure that the message content wasn’t replaced.
3. Google Sign-in
Provider: Google serves as a trusted identity provider, enabling authentication via OAuth2/OIDC.
4. Apple Sign-in
Provider: Apple acts as a trusted identity provider, facilitating authentication via OAuth2/OIDC.
Single Sign-On (SSO)
SSO facilitates cross-domain user authentication. When a user navigates from one domain (e.g., "portal") to another (e.g., "store") part of the ecosystem, seamless authentication occurs, even with different backends. The Authentication Service acts as a verified identity provider, achieved through the code grant flow utilizing OAuth2/OIDC scheme. This feature caters to cross-domain authentication and authenticating through WebSocket connections in standalone applications (e.g., mobile game apps).
Social Media Account Linking
Users have the option to link their Twitter and Discord accounts to their profile. Account ownership verification occurs through the respective provider's authentication, leveraging OAuth2/OIDC. Users can connect/disconnect their accounts any time with no limitation, except the fact that those accounts should be unique across the application.
Profile Management
The service employs a single profile for all login methods, ensuring a unified entry point and consolidating user accounts. Users can log in through any available method, maintaining the same profile. However, certain limitations apply:
Wallet Changes: Users cannot change wallets but can only link them if previously logged in via email, Google, or Apple without a wallet linked in their profile.
Email Changes: Users can change their email (verified via confirmation email) only if they haven't logged in through other methods linked to that email (e.g., Apple/Google).
Profile Image: The user's profile incorporates their Twitter avatar.
User-Controlled Name: Users have the autonomy to modify their displayed name within the Souls Club platform, allowing for personalized identification.
Moderation Protocol: Any changes made to the displayed name undergo moderation to detect and prevent the inclusion of harmful or inappropriate content. This moderation process ensures the platform maintains a safe and respectful environment for all users.
Token Rotation Mechanism
Service employs a token rotation mechanism, ensuring users can remain virtually logged in continuously without the need for repeated logins.
Continuous Authentication: Users have prolonged login sessions, minimizing the need for frequent manual logins.
Token Lifespan: The access token has a lifespan of 15 minutes, ensuring short-term access to the system. Refresh token remains valid for 21 days. New refresh is generated with every refresh request while the old one becomes invalid.
This token rotation mechanism strikes a balance between user convenience and stringent security standards, providing a seamless login experience while safeguarding user accounts effectively.
User Permissions and Admin Access
Authorization system currently supports two types of permissions: regular user and admin. Access to admin-specific endpoints requires not only authentication but also the presence of admin-level permissions.
Admin Endpoint Functions
Read-Only Operations: These endpoints facilitate actions like searching, sorting, and grouping user data.
Support Functions: Essential for support teams to troubleshoot and resolve user issues efficiently.
These endpoints cater to administrative functions, enabling read-only operations on user data. They include functionalities such as search, sorting, and grouping, primarily utilized by support teams to address user issues effectively.
Technical Architecture Overview
Introduction
The architecture of the application follows a modular and layered design, emphasizing separation of concerns and maintainability. The core components include storage layers for PostgreSQL and Redis, repository layers for data access, service layers for business logic, use case layers for workflow orchestration, and presentation layers for handling HTTP requests.
Layers
1. Storage Layer
Database: Utilizes the databases library and SQLAlchemy for low-level communication with PostgreSQL.
Redis Manager: Acts as a repository class for Redis storage, handling tasks such as connection management and pub/sub operations.
2. Repository Layer
Provides a clean interface for data access through repositories with methods like get, update, and create. Implements specific methods for concrete models, ensuring a consistent and standardized approach to data retrieval and manipulation.
3. Service Layer
Defines service interfaces as contract keepers for communication with services. Service implementations orchestrate, validate, and store data using injected repositories and the Redis manager.
4. Use Case Layer
Orchestrates workflow by making calls to injected services. Uses services through their interfaces, enabling flexibility and reusability.
5. IoC Container
Facilitates dependency injection, allowing registration of configurations, repositories, and use cases. Enables service registration as implementations of interfaces, promoting flexibility and ease of service replacement.
6. Presentation Layer
Schemas and Routers: Routers are thin and injected with corresponding specific use cases. Handle user requests, pass data to the use case execution method, and return use case responses.
Auth Middleware
Custom ASGI auth middleware handles authentication using access tokens. Authentication logic is encapsulated in a dedicated TokenService, providing modular and reusable authentication handling.
Error Handling
Custom error handler catches service layer errors and automatically produces corresponding HTTP errors with the correct status codes. Provides consistency in error responses, simplifying code and ensuring a standardized error format. Enables ease of testing for error scenarios, aiding in maintaining the application's robustness.
Diamonds Service Documentation
Solution Architecture Overview
The Diamonds Service is designed to empower users by allowing them to collect diamonds (points), manage streaks, and earn referral bonuses. It ensures accurate tracking of user interactions, precise reward calculations, and provides real-time feedback through asynchronous updates via WebSocket connections. Leveraging JWT-based authentication integrated with the Auth Service, the Diamonds Service maintains secure and seamless user experiences without the overhead of managing authentication mechanisms independently.
Core Features
1. Diamond Collection
Functionality: Users can earn diamonds through various interactions within the ecosystem.
Mechanism: Diamonds are accumulated based on predefined actions and activities, incentivizing user engagement.
2. Streak Management
Functionality: Tracks consecutive days of user activity to maintain streaks.
Benefits: Encourages regular user participation by rewarding continuous engagement.
3. Referral Bonuses
Functionality: Calculates and allocates bonuses when users refer others to the platform.
Mechanism: Utilizes referral codes and tracks successful invitations to distribute rewards accordingly.
Real-Time Feedback and Asynchronous Updates
WebSocket Integration: Enables real-time communication between the Diamonds Service and client applications, ensuring users receive immediate feedback on their diamond balance, streaks, and referral bonuses.
Apache Pulsar: Facilitates the asynchronous handling of updates and commands, ensuring scalability and reliability in message processing.
Authentication and Security
JWT-Based Authentication: Utilizes JWT access and refresh tokens issued by the Auth Service.
Security Assurance: Relies on shared JWT secrets to validate tokens, ensuring that only properly signed and unexpired tokens grant access. The service extracts auth_user_uuid from the JWT payload to associate actions with the correct user.
CQRS Architecture
The Diamonds Service adopts a Command Query Responsibility Segregation (CQRS) architecture to separate read and write operations, enhancing scalability and maintainability.
1. diamonds-domain
Role: Acts as a common library used by other components of the service.
Components:
Database Interaction: Classes and utilities for interacting with PostgreSQL.
Models: Defines the data structures and schemas.
Redis Manager: Handles caching and quick data retrieval using Redis.
Pulsar Manager: Manages communication with Apache Pulsar for message brokering.
Configurations and Constants: Centralized settings and constant values used across the service.
2. diamonds-service
Type: Read-only service built with FastAPI.
Responsibilities:
Client Communication: Manages all interactions with client applications.
Data Retrieval: Reads data from PostgreSQL and Redis cache to serve client requests.
Request Validation: Ensures incoming requests meet the necessary criteria before processing.
Pulsar Messaging: Sends messages to Pulsar for the worker to process commands.
WebSocket Management: Maintains WebSocket connections with clients and subscribes to Pulsar topics for real-time updates.
3. diamonds-worker
Type: Read-write service developed in pure Python.
Responsibilities:
Message Processing: Listens to Pulsar messages from the Diamonds Service and executes commands.
Data Updates: Makes necessary updates to PostgreSQL and Redis cache based on commands.
Consistency and Idempotency: Ensures commands are processed exactly once using an event-driven approach and maintains an event log to prevent double processing or malicious updates.
Cache Management: Implements a Write-Through caching strategy to keep Redis in sync with PostgreSQL.
Real-Time Updates: Publishes updated profile data to Pulsar, which the Diamonds Service consumes and forwards to clients via WebSockets.
Concurrency Control: Subscribes to partitioned command topics based on auth_user_uuid to ensure sequential command processing per user, avoiding the need for exclusive database locks.
Technical Architecture Overview
Introduction
The Diamonds Service architecture emphasizes modularity, separation of concerns, and maintainability. It is structured as a monorepository following the CQRS pattern, ensuring clear delineation between read and write operations. Core components include PostgreSQL for persistent storage, Redis for caching, Apache Pulsar for message brokering, and WebSockets for real-time client communication.
Layers
1. Storage Layer
PostgreSQL:
Usage: Serves as the primary relational database for storing user data, diamond transactions, streak records, and referral information.
Interaction: Utilizes SQLAlchemy for ORM-based interactions, providing a robust and scalable database solution.
Redis:
Usage: Functions as an in-memory data store for caching frequently accessed data, reducing latency and database load.
Manager: Handled by the Redis Manager within the diamonds-domain, facilitating efficient cache operations and pub/sub mechanisms.
2. Repository Layer
Purpose: Provides a clean and abstracted interface for data access operations.
Components:
Repositories: Implement methods such as get, update, create tailored to specific models.
Consistency: Ensures a standardized approach to data manipulation across different parts of the service.
3. Service Layer
Purpose: Encapsulates business logic and orchestrates interactions between repositories and other components.
Components:
Service Interfaces: Define contracts for various services, ensuring consistent and interchangeable implementations.
Implementations: Validate data, enforce business rules, and manage transactional operations using injected repositories and managers.
4. Use Case Layer
Purpose: Manages workflow orchestration by coordinating service layer interactions to fulfill specific business use cases.
Functionality: Executes complex operations by invoking multiple services, ensuring that each use case is handled efficiently and coherently.
5. IoC Container
Function: Facilitates dependency injection, allowing for the dynamic registration and resolution of dependencies.
Benefits: Promotes flexibility and ease of testing by decoupling service implementations from their dependencies.
6. Presentation Layer
Components:
Schemas: Define the structure of request and response payloads using Pydantic models.
Routers: Handle incoming HTTP and WebSocket requests, injecting the necessary use cases and responding appropriately.
Functionality: Acts as the entry point for client interactions, delegating processing to the underlying use case execution methods.
Communication and Data Flow
Pulsar Messaging:
Purpose: Acts as the central message broker facilitating communication between diamonds-service and diamonds-worker.
Topics:
Commands Topic: Receives commands from the Diamonds Service to be processed by the worker.
Updates Topic: Publishes updated user data after processing, which the service consumes to notify clients in real-time.
WebSockets:
Purpose: Provides persistent connections for real-time updates, ensuring users receive immediate feedback on their diamond-related activities.
Integration: Subscribes to the Updates Topic in Pulsar and forwards relevant messages to connected clients seamlessly.
Data Management
Event-Driven Approach:
Event Log: Maintains a comprehensive log of all events to ensure idempotency and prevent duplicate processing.
Write-Through Caching: Ensures that all cache updates occur simultaneously with database changes, maintaining consistency between Redis and PostgreSQL.
Consistency Models:
Eventual Consistency: Guarantees that, over time, all components will reflect the same state, suitable for the asynchronous nature of the service.
Idempotency: Ensures that repeated processing of the same command does not adversely affect the system, safeguarding against duplicate or malicious requests.
Security Measures
JWT Validation:
Mechanism: Validates JWT access and refresh tokens against the shared secret with the Auth Service, ensuring only authenticated requests are processed.
Data Extraction: Retrieves auth_user_uuid from the JWT payload to associate actions with the correct user context.
Access Control:
Endpoints: Restricts access to endpoints based on token validity and user permissions managed by the Auth Service.
Data Protection: Ensures sensitive user data is only accessible to authorized components and services within the system.
Error Handling
Centralized Error Management:
Custom Error Handlers: Capture exceptions at various layers and translate them into standardized HTTP responses with appropriate status codes.
Consistency: Provides uniform error responses across the service, simplifying client-side error handling and improving debuggability.
Resilience:
Retry Mechanisms: Implements retry strategies for transient failures in external dependencies like PostgreSQL, Redis, or Pulsar.
Fallback Strategies: Defines fallback procedures to maintain service availability and integrity in case of partial system failures.
Scalability and Performance
CQRS Architecture: Separates read and write operations, allowing each to be scaled independently based on demand.
Asynchronous Processing: Utilizes Apache Pulsar and WebSockets to handle high-throughput and low-latency requirements, ensuring the service remains responsive under load.
Cache Optimization: Leverages Redis to minimize database hits, reducing latency and enhancing overall system performance.
Deployment and Maintenance
Monorepository Structure: Manages all components of the Diamonds Service within a single repository, simplifying version control and dependency management.
Continuous Integration/Continuous Deployment (CI/CD): Implements automated pipelines for testing, building, and deploying the service, ensuring rapid and reliable updates.
Monitoring and Logging:
Observability: Integrates monitoring tools to track system metrics, performance, and health.
Logging: Maintains comprehensive logs for all service operations, aiding in troubleshooting and performance tuning.
Conclusion
The Diamonds Service is a robust, scalable, and secure platform designed to enhance user engagement through diamond collection, streak management, and referral bonuses. By leveraging a CQRS architecture, real-time communication via WebSockets, and an event-driven approach with Apache Pulsar, the service ensures high performance and reliability. Integrated seamlessly with the Auth Service for authentication, the Diamonds Service maintains a clear separation of concerns, promoting maintainability and ease of evolution within the ecosystem.