Designing a highly efficient, scalable, and maintainable task management system with verifiable and non-verifiable tasks requires careful consideration of architecture, data modeling, caching strategies, and verifier implementation. Below is a comprehensive approach to designing and developing such a system, including clean and robust code examples using Python with popular frameworks and best practices.
1. System Architecture Overview
Components:
-
Tasks Service:
- Tasks Table: Stores all possible tasks with their details and verifier information.
- User Profile: Stores user-specific data, including completed tasks as a JSONB field.
-
Caching Layer:
- Cache (e.g., Redis): Caches the list of tasks to minimize DB calls.
-
Verifier System:
- Verifier Classes: Handle the verification logic for verifiable tasks.
- Dispatcher: Routes verification requests to the appropriate verifier.
-
CQRS and Messaging:
- Command Side: Handles task commands (e.g., completing a task).
- Query Side: Fetches tasks, utilizing caching.
- Message Broker (e.g., Pulsar): Manages asynchronous operations like rewards.
Workflow:
-
Fetching Tasks:
- Check the cache for the list of tasks.
- If not cached, fetch from the DB and cache it.
- Retrieve the user's completed tasks from the JSONB field.
- Merge the tasks with the user's completion state.
-
Completing a Task:
- User completes a task on the frontend.
- Sends a
task_completed command.
- If verifiable, dispatch to the appropriate verifier.
- Upon successful verification, update the user's completed tasks and post a reward message.
2. Data Modeling
Tasks Table:
CREATE TABLE tasks (
uuid UUID PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
verifier_name VARCHAR(255), -- NULL for non-verifiable tasks
verifier_value VARCHAR(255), -- Parameter for the verifier
type VARCHAR(50) NOT NULL, -- 'verifiable' or 'non-verifiable'
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
Users Table:
CREATE TABLE users (
uuid UUID PRIMARY KEY,
profile JSONB, -- Stores user-specific data including completed tasks
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
Example profile JSONB Structure:
{
"completed_tasks": ["uuid1", "uuid2", ...],
"ref_quantity": 10,
"streak": 5,
// Other profile-related data
}
3. Caching Strategy
Use Redis as the caching layer to store the list of tasks with a long TTL (e.g., 24 hours). Utilize cache invalidation strategies based on task updates.
- Cache Key:
tasks_list
- TTL: 86400 seconds (24 hours)
Fetching Tasks:
- Attempt to retrieve
tasks_list from Redis.
- If not present, fetch from the database, store in Redis, and return.
4. Verifier System Design
Verifier Interface:
Define a base Verifier interface that all verifiers will implement. This ensures consistency and ease of extension.
from abc import ABC, abstractmethod
from typing import Any
class VerificationContext:
def __init__(self, user_profile: dict):
self.user_profile = user_profile
# Add more context attributes as needed
class Verifier(ABC):
@abstractmethod
def verify(self, value: Any, context: VerificationContext) -> bool:
pass
Dispatcher:
A dispatcher that maps verifier_name to the corresponding verifier class and executes the verification.
class VerifierDispatcher:
_registry = {}
@classmethod
def register(cls, verifier_name: str):
def inner_wrapper(wrapped_class):
cls._registry[verifier_name] = wrapped_class()
return wrapped_class
return inner_wrapper
@classmethod
def get_verifier(cls, verifier_name: str) -> Verifier:
verifier = cls._registry.get(verifier_name)
if not verifier:
raise ValueError(f"No verifier found for {verifier_name}")
return verifier
@classmethod
def verify(cls, verifier_name: str, value: Any, context: VerificationContext) -> bool:
verifier = cls.get_verifier(verifier_name)
return verifier.verify(value, context)
Verifier Implementations:
Implement verifiers by extending the Verifier base class and registering them with the dispatcher.
Example Verifier Implementations:
# Verifiers that check simple conditions based on user profile
@VerifierDispatcher.register('invites_verifier')
class InvitesVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('ref_quantity', 0) >= value
@VerifierDispatcher.register('streak_verifier')
class StreakVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('streak', 0) >= value
@VerifierDispatcher.register('level_verifier')
class LevelVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('level', 0) >= value
@VerifierDispatcher.register('purchase_verifier')
class PurchaseVerifier(Verifier):
def verify(self, value: float, context: VerificationContext) -> bool:
return context.user_profile.get('total_purchases', 0.0) >= value
# Verifiers that require external API calls
import requests
@VerifierDispatcher.register('email_verifier')
class EmailVerifier(Verifier):
def verify(self, value: bool, context: VerificationContext) -> bool:
user_email = context.user_profile.get('email', '')
if not user_email:
return False
response = requests.get(f"https://api.emailvalidation.com/validate?email={user_email}")
if response.status_code == 200:
data = response.json()
return data.get('is_valid', False) == value
return False
@VerifierDispatcher.register('social_media_verifier')
class SocialMediaVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
user_id = context.user_profile.get('social_media_id')
if not user_id:
return False
# Example API call to check number of followers
response = requests.get(f"https://api.socialmedia.com/users/{user_id}/followers")
if response.status_code == 200:
data = response.json()
return data.get('follower_count', 0) >= value
return False
# Additional verifiers can be implemented similarly...
# For brevity, here are placeholders for additional verifiers
@VerifierDispatcher.register('content_completed_verifier')
class ContentCompletedVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('content_completed', 0) >= value
@VerifierDispatcher.register('quiz_passed_verifier')
class QuizPassedVerifier(Verifier):
def verify(self, value: bool, context: VerificationContext) -> bool:
return context.user_profile.get('quiz_passed', False) == value
# ... Add up to 20 verifiers following the same pattern
Handling Asynchronous Verifiers:
For verifiers that require external API calls, it's advisable to handle them asynchronously to prevent blocking the main thread. Using async/await with an asynchronous HTTP client like aiohttp can achieve this.
Async Verifier Example:
import aiohttp
import asyncio
@VerifierDispatcher.register('async_email_verifier')
class AsyncEmailVerifier(Verifier):
async def verify(self, value: bool, context: VerificationContext) -> bool:
user_email = context.user_profile.get('email', '')
if not user_email:
return False
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.emailvalidation.com/validate?email={user_email}") as response:
if response.status == 200:
data = await response.json()
return data.get('is_valid', False) == value
return False
Note: Integration of asynchronous verifiers requires the overall verification pipeline to support asynchronous operations.
5. Implementation Details
Technology Stack:
- Backend Framework: FastAPI (for its async capabilities and performance)
- Database: PostgreSQL (supports JSONB and UUID)
- Cache: Redis
- Message Broker: Pulsar
- ORM: SQLAlchemy (with async support)
Sample Implementation using FastAPI and SQLAlchemy
Project Structure:
.
├── app
│ ├── main.py
│ ├── models.py
│ ├── schemas.py
│ ├── database.py
│ ├── cache.py
│ ├── verifiers
│ │ ├── base.py
│ │ ├── dispatcher.py
│ │ ├── invities_verifier.py
│ │ ├── ... (other verifiers)
│ ├── services
│ │ ├── task_service.py
│ │ ├── user_service.py
│ │ └── verification_service.py
│ └── messaging
│ └── publisher.py
└── requirements.txt
Key Components:
- Database Configuration (
database.py):
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
import os
DATABASE_URL = os.getenv('DATABASE_URL', 'postgresql+asyncpg://user:password@localhost/db')
engine = create_async_engine(DATABASE_URL, echo=False, pool_size=20, max_overflow=0)
SessionLocal = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
- Cache Configuration (
cache.py):
import aioredis
import os
REDIS_URL = os.getenv('REDIS_URL', 'redis://localhost:6379')
redis = aioredis.from_url(REDIS_URL, encoding="utf-8", decode_responses=True)
- Models (
models.py):
from sqlalchemy import Column, String, Text, DateTime
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.ext.declarative import declarative_base
import uuid
from datetime import datetime
Base = declarative_base()
class Task(Base):
__tablename__ = 'tasks'
uuid = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String(255), nullable=False)
description = Column(Text)
verifier_name = Column(String(255), nullable=True)
verifier_value = Column(String(255), nullable=True)
type = Column(String(50), nullable=False) # 'verifiable' or 'non-verifiable'
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class User(Base):
__tablename__ = 'users'
uuid = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
profile = Column(JSONB, default=dict)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
- Schemas (
schemas.py):
from pydantic import BaseModel, UUID4
from typing import List, Optional
class TaskSchema(BaseModel):
uuid: UUID4
name: str
description: Optional[str] = None
verifier_name: Optional[str] = None
verifier_value: Optional[str] = None
type: str
class Config:
orm_mode = True
class UserProfileSchema(BaseModel):
completed_tasks: List[UUID4] = []
ref_quantity: int = 0
streak: int = 0
# Add other profile fields as necessary
class UserSchema(BaseModel):
uuid: UUID4
profile: UserProfileSchema
class Config:
orm_mode = True
- Verifier System (
verifiers/base.py, dispatch.py, etc.):
(As shown earlier in the Verifier System Design section.)
- Services:
- Task Service (
services/task_service.py):
from app.database import SessionLocal
from app.models import Task
from app.schemas import TaskSchema
from app.cache import redis
from typing import List
import json
TASKS_CACHE_KEY = 'tasks_list'
TASKS_CACHE_TTL = 86400 # 24 hours
async def get_all_tasks() -> List[TaskSchema]:
cached_tasks = await redis.get(TASKS_CACHE_KEY)
if cached_tasks:
tasks_data = json.loads(cached_tasks)
return [TaskSchema(**task) for task in tasks_data]
async with SessionLocal() as session:
result = await session.execute(select(Task))
tasks = result.scalars().all()
tasks_data = [TaskSchema.from_orm(task).dict() for task in tasks]
await redis.set(TASKS_CACHE_KEY, json.dumps(tasks_data), ex=TASKS_CACHE_TTL)
return [TaskSchema(**task) for task in tasks_data]
- User Service (
services/user_service.py):
from app.database import SessionLocal
from app.models import User
from app.schemas import UserSchema
from typing import Optional
async def get_user(user_uuid: str) -> Optional[UserSchema]:
async with SessionLocal() as session:
user = await session.get(User, user_uuid)
if user:
return UserSchema.from_orm(user)
return None
async def update_user_completed_task(user_uuid: str, task_uuid: str):
async with SessionLocal() as session:
user = await session.get(User, user_uuid)
if user:
completed_tasks = user.profile.get('completed_tasks', [])
if task_uuid not in completed_tasks:
completed_tasks.append(task_uuid)
user.profile['completed_tasks'] = completed_tasks
session.add(user)
await session.commit()
- Verification Service (
services/verification_service.py):
from app.verifiers.dispatcher import VerifierDispatcher
from app.schemas import UserSchema
from app.verifiers.base import VerificationContext
async def verify_task(task, user: UserSchema) -> bool:
if task.type == 'non-verifiable':
return True
verifier_name = task.verifier_name
verifier_value = task.verifier_value
if not verifier_name or not verifier_value:
return False # Incomplete verifier information
context = VerificationContext(user_profile=user.profile)
# Handle async verifiers
verifier = VerifierDispatcher.get_verifier(verifier_name)
if hasattr(verifier, 'verify') and asyncio.iscoroutinefunction(verifier.verify):
return await VerifierDispatcher.verify(verifier_name, verifier_value, context)
# Synchronous verification
return VerifierDispatcher.verify(verifier_name, verifier_value, context)
- API Endpoints (
main.py):
from fastapi import FastAPI, HTTPException, Depends
from app.schemas import TaskSchema, UserSchema
from app.services.task_service import get_all_tasks
from app.services.user_service import get_user, update_user_completed_task
from app.services.verification_service import verify_task
from typing import List
import uuid
import json
app = FastAPI()
@app.get("/tasks", response_model=List[TaskSchema])
async def fetch_tasks(user_uuid: str):
user = await get_user(user_uuid)
if not user:
raise HTTPException(status_code=404, detail="User not found")
tasks = await get_all_tasks()
completed_tasks_set = set(str(task_uuid) for task_uuid in user.profile.get('completed_tasks', []))
# Merge task completion state
tasks_with_state = []
for task in tasks:
task_dict = task.dict()
task_dict['completed'] = str(task.uuid) in completed_tasks_set
tasks_with_state.append(task_dict)
return tasks_with_state
@app.post("/tasks/complete")
async def complete_task(user_uuid: str, task_uuid: str):
try:
task_uuid_obj = uuid.UUID(task_uuid)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid Task UUID")
user = await get_user(user_uuid)
if not user:
raise HTTPException(status_code=404, detail="User not found")
# Fetch the task details, possibly from cache
tasks = await get_all_tasks()
task = next((t for t in tasks if t.uuid == task_uuid_obj), None)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
# Verify the task if it's verifiable
if task.type == 'verifiable':
is_valid = await verify_task(task, user)
if not is_valid:
raise HTTPException(status_code=400, detail="Task verification failed")
# Update user's completed tasks
await update_user_completed_task(user_uuid, str(task_uuid_obj))
# Post a reward message to Pulsar
# Assuming a publish_reward function is defined
await publish_reward(user_uuid, task.uuid)
return {"status": "Task completed and reward claimed"}
# Placeholder for the reward publishing function
async def publish_reward(user_uuid: str, task_uuid: uuid.UUID):
# Implement Pulsar publishing logic here
pass
- Message Publishing (
messaging/publisher.py):
from pulsar import Client
import os
import json
PULSAR_URL = os.getenv('PULSAR_URL', 'pulsar://localhost:6650')
REWARD_TOPIC = os.getenv('REWARD_TOPIC', 'reward-topic')
client = Client(PULSAR_URL)
producer = client.create_producer(REWARD_TOPIC)
async def publish_reward(user_uuid: str, task_uuid: str):
message = {
"user_uuid": user_uuid,
"task_uuid": str(task_uuid),
"reward_type": "task_completion",
"timestamp": datetime.utcnow().isoformat()
}
producer.send(json.dumps(message).encode('utf-8'))
- Extending with Additional Verifiers:
To add more verifiers, simply create new verifier classes following the same pattern and register them with the dispatcher.
Example:
@VerifierDispatcher.register('daily_login_verifier')
class DailyLoginVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('daily_logins', 0) >= value
@VerifierDispatcher.register('share_on_social_verifier')
class ShareOnSocialVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('social_shares', 0) >= value
6. Best Practices and Optimization Strategies
a. Minimize Database Calls:
- Caching: Utilize Redis to cache the list of tasks, reducing repetitive database queries.
- Selective Loading: Only load user profile data necessary for verification to minimize data transfer.
b. Efficient Data Storage:
- JSONB: Use JSONB for storing completed tasks and profile data, allowing flexible and efficient querying.
- UUIDs: Utilize UUIDs for unique identification, ensuring scalability across distributed systems.
c. Asynchronous Processing:
- Async Verifiers: Implement asynchronous verifiers for tasks requiring external API calls to prevent blocking.
- Message Broker: Use Pulsar to handle reward processing asynchronously, decoupling it from the main request flow.
d. Scalable Verifier Dispatching:
- Dynamic Registration: Allow dynamic registration of verifier classes to facilitate easy extension without modifying the dispatcher.
- Thread Safety: Ensure that the dispatcher and verifiers are thread-safe, especially in a high-concurrency environment.
e. Error Handling and Retries:
- Robust Error Handling: Implement comprehensive error handling in verifiers and services to gracefully handle failures.
- Retry Mechanisms: For external API calls, implement retry strategies with exponential backoff to handle transient failures.
f. Security Considerations:
- Input Validation: Validate all incoming data to prevent injection attacks.
- Secure Communication: Use HTTPS for all external API calls and secure channels for internal communication.
g. Monitoring and Logging:
- Logging: Implement detailed logging for monitoring task completions, verifier executions, and reward postings.
- Metrics: Track metrics such as task completion rates, verifier performance, and message broker throughput.
h. Testing:
- Unit Tests: Write unit tests for verifiers, services, and API endpoints to ensure correctness.
- Integration Tests: Test the interaction between different components, including cache, database, and external APIs.
- Load Testing: Perform load testing to ensure the system can handle high concurrency and data volumes.
7. Conclusion
The proposed system design ensures efficient data storage, minimal database interactions, and scalable verification mechanisms. By leveraging modern frameworks like FastAPI, asynchronous programming, and a robust caching layer, the application can handle high loads with optimal resource utilization. The verifier system is designed to be easily extendable, allowing seamless addition of new task types and verification logic.
Below is the complete sample code integrating all components for a working prototype.
Complete Sample Code
app/verifiers/dispatcher.py
from typing import Any
from .base import Verifier
import asyncio
class VerifierDispatcher:
_registry = {}
@classmethod
def register(cls, verifier_name: str):
def inner_wrapper(wrapped_class):
cls._registry[verifier_name] = wrapped_class()
return wrapped_class
return inner_wrapper
@classmethod
def get_verifier(cls, verifier_name: str) -> Verifier:
verifier = cls._registry.get(verifier_name)
if not verifier:
raise ValueError(f"No verifier found for {verifier_name}")
return verifier
@classmethod
async def verify(cls, verifier_name: str, value: Any, context: Any) -> bool:
verifier = cls.get_verifier(verifier_name)
if asyncio.iscoroutinefunction(verifier.verify):
return await verifier.verify(value, context)
return verifier.verify(value, context)
app/verifiers/base.py
from abc import ABC, abstractmethod
from typing import Any
class VerificationContext:
def __init__(self, user_profile: dict):
self.user_profile = user_profile
# Add more context as necessary
class Verifier(ABC):
@abstractmethod
def verify(self, value: Any, context: VerificationContext) -> bool:
pass
app/verifiers/invites_verifier.py
from .dispatcher import VerifierDispatcher
from .base import Verifier, VerificationContext
@VerifierDispatcher.register('invites_verifier')
class InvitesVerifier(Verifier):
def verify(self, value: int, context: VerificationContext) -> bool:
return context.user_profile.get('ref_quantity', 0) >= value
app/verifiers/email_verifier.py
import aiohttp
from .dispatcher import VerifierDispatcher
from .base import Verifier, VerificationContext
@VerifierDispatcher.register('email_verifier')
class EmailVerifier(Verifier):
async def verify(self, value: bool, context: VerificationContext) -> bool:
user_email = context.user_profile.get('email', '')
if not user_email:
return False
async with aiohttp.ClientSession() as session:
try:
async with session.get(f"https://api.emailvalidation.com/validate?email={user_email}") as response:
if response.status == 200:
data = await response.json()
return data.get('is_valid', False) == value
except Exception as e:
# Log exception
return False
return False
app/services/verification_service.py
from app.verifiers.dispatcher import VerifierDispatcher
from app.schemas import UserSchema
from app.verifiers.base import VerificationContext
import asyncio
async def verify_task(task, user: UserSchema) -> bool:
if task.type == 'non-verifiable':
return True
verifier_name = task.verifier_name
verifier_value = task.verifier_value
if not verifier_name or not verifier_value:
return False # Incomplete verifier information
context = VerificationContext(user_profile=user.profile)
try:
is_valid = await VerifierDispatcher.verify(verifier_name, verifier_value, context)
return is_valid
except Exception as e:
# Log exception
return False
app/main.py
from fastapi import FastAPI, HTTPException, Depends
from app.schemas import TaskSchema, UserSchema
from app.services.task_service import get_all_tasks
from app.services.user_service import get_user, update_user_completed_task
from app.services.verification_service import verify_task
from typing import List
import uuid
import json
import asyncio
from app.messaging.publisher import publish_reward
app = FastAPI()
@app.get("/tasks", response_model=List[dict])
async def fetch_tasks(user_uuid: str):
user = await get_user(user_uuid)
if not user:
raise HTTPException(status_code=404, detail="User not found")
tasks = await get_all_tasks()
completed_tasks_set = set(str(task_uuid) for task_uuid in user.profile.get('completed_tasks', []))
# Merge task completion state
tasks_with_state = []
for task in tasks:
task_dict = task.dict()
task_dict['completed'] = str(task.uuid) in completed_tasks_set
tasks_with_state.append(task_dict)
return tasks_with_state
@app.post("/tasks/complete")
async def complete_task(user_uuid: str, task_uuid: str):
try:
task_uuid_obj = uuid.UUID(task_uuid)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid Task UUID")
user = await get_user(user_uuid)
if not user:
raise HTTPException(status_code=404, detail="User not found")
# Fetch the task details, possibly from cache
tasks = await get_all_tasks()
task = next((t for t in tasks if t.uuid == task_uuid_obj), None)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
# Verify the task if it's verifiable
if task.type == 'verifiable':
is_valid = await verify_task(task, user)
if not is_valid:
raise HTTPException(status_code=400, detail="Task verification failed")
# Update user's completed tasks
await update_user_completed_task(user_uuid, str(task_uuid_obj))
# Post a reward message to Pulsar
await publish_reward(user_uuid, str(task_uuid_obj))
return {"status": "Task completed and reward claimed"}
app/messaging/publisher.py
from pulsar import Client
import os
import json
from datetime import datetime
PULSAR_URL = os.getenv('PULSAR_URL', 'pulsar://localhost:6650')
REWARD_TOPIC = os.getenv('REWARD_TOPIC', 'reward-topic')
client = Client(PULSAR_URL)
producer = client.create_producer(REWARD_TOPIC)
async def publish_reward(user_uuid: str, task_uuid: str):
message = {
"user_uuid": user_uuid,
"task_uuid": task_uuid,
"reward_type": "task_completion",
"timestamp": datetime.utcnow().isoformat()
}
producer.send(json.dumps(message).encode('utf-8'))
app/services/task_service.py
from app.database import SessionLocal
from app.models import Task
from app.schemas import TaskSchema
from app.cache import redis
from typing import List
import json
from sqlalchemy.future import select
TASKS_CACHE_KEY = 'tasks_list'
TASKS_CACHE_TTL = 86400 # 24 hours
async def get_all_tasks() -> List[TaskSchema]:
cached_tasks = await redis.get(TASKS_CACHE_KEY)
if cached_tasks:
tasks_data = json.loads(cached_tasks)
return [TaskSchema(**task) for task in tasks_data]
async with SessionLocal() as session:
result = await session.execute(select(Task))
tasks = result.scalars().all()
tasks_data = [TaskSchema.from_orm(task).dict() for task in tasks]
await redis.set(TASKS_CACHE_KEY, json.dumps(tasks_data), ex=TASKS_CACHE_TTL)
return [TaskSchema(**task) for task in tasks_data]
app/services/user_service.py
from app.database import SessionLocal
from app.models import User
from app.schemas import UserSchema
from typing import Optional
async def get_user(user_uuid: str) -> Optional[UserSchema]:
async with SessionLocal() as session:
user = await session.get(User, user_uuid)
if user:
return UserSchema.from_orm(user)
return None
async def update_user_completed_task(user_uuid: str, task_uuid: str):
async with SessionLocal() as session:
user = await session.get(User, user_uuid)
if user:
completed_tasks = user.profile.get('completed_tasks', [])
if task_uuid not in completed_tasks:
completed_tasks.append(task_uuid)
user.profile['completed_tasks'] = completed_tasks
session.add(user)
await session.commit()
app/cache.py
import aioredis
import os
REDIS_URL = os.getenv('REDIS_URL', 'redis://localhost:6379')
redis = aioredis.from_url(REDIS_URL, encoding="utf-8", decode_responses=True)
requirements.txt
fastapi
uvicorn
sqlalchemy[asyncio]
asyncpg
aioredis
pulsar-client
pydantic
aiohttp
Final Notes
-
Environment Variables: Ensure that environment variables like DATABASE_URL, REDIS_URL, PULSAR_URL, and REWARD_TOPIC are correctly set in your deployment environment.
-
Database Migrations: Use tools like Alembic to manage database migrations for evolving the tasks and users tables.
-
Security Enhancements: Implement authentication and authorization mechanisms to secure the API endpoints.
-
Scalability Considerations: Deploy the application using scalable platforms (e.g., Kubernetes) and monitor resource usage to adjust scaling policies as needed.
By following this design and implementation strategy, you can build a robust, efficient, and scalable task management system capable of handling verifiable and non-verifiable tasks with optimal resource utilization.