System Design for a Parking Spot Exchange Application Using Domain-Driven Design (DDD)
Overview
You are designing a Java application that facilitates the exchange of public parking spots between users. By following Domain-Driven Design (DDD) principles, we'll structure the system into well-defined domains and bounded contexts to manage complexity and ensure scalability.
Core Requirements
- User Actions:
- Leaving User: Signals they are leaving a parking spot and provides an estimated departure time.
- Arriving User: Searches for available spots, reserves one, and goes to take the spot.
- Rewards System:
- Leaving users are rewarded (variable amount) when their spot is successfully taken by an arriving user.
- Additional Considerations:
- Real-time notifications.
- Handling cancellations and no-shows.
- User ratings and feedback.
High-Level Architecture
- Frontend:
- Mobile applications (iOS/Android) for user interaction.
- Backend:
- Microservices or modular monolith built with Spring Boot.
- Database:
- Relational database (e.g., PostgreSQL) or NoSQL database (e.g., MongoDB) for persistence.
- External Services:
- Mapping and geolocation services.
- Payment gateway for processing rewards.
Domain-Driven Design Components
1. Ubiquitous Language
- User: An individual using the app.
- Leaving User: A user vacating a parking spot.
- Arriving User: A user seeking a parking spot.
- Parking Spot Availability: The state indicating a spot will be free.
- Reservation: An arriving user's claim to an available spot.
- Reward: Compensation given to the leaving user.
- Notification: Messages sent to users regarding spot availability or status changes.
2. Bounded Contexts
- User Context
- Manages user profiles, authentication, and ratings.
- Parking Context
- Handles parking spot availability, reservations, and status updates.
- Reward Context
- Manages the reward mechanism and transactions.
- Notification Context
- Takes care of all user notifications.
- Mapping Context
- Interacts with external mapping services for geolocation.
3. Entities, Value Objects, and Aggregates
User Context
- Entity:
User
- Attributes:
userId (unique identifier)
name
email
phoneNumber
paymentInfo (value object)
rating
- Aggregate Root:
User
- Repository:
UserRepository
- Service:
UserService
Parking Context
- Entity:
Availability
- Attributes:
availabilityId (unique identifier)
leavingUserId
location (value object with latitude and longitude)
estimatedLeavingTime
status (Available, Reserved, Taken, Canceled)
reservedByUserId
timestamps (createdAt, updatedAt)
- Entity:
Reservation
- Attributes:
reservationId
availabilityId
arrivingUserId
status (Active, Completed, Canceled)
timestamps
- Aggregate Root:
Availability
- Repository:
AvailabilityRepository
- Service:
ParkingService
Reward Context
- Entity:
Reward
- Attributes:
rewardId
fromUserId (leaving user)
toUserId (arriving user)
amount
timestamp
status (Pending, Completed, Failed)
- Aggregate Root:
Reward
- Repository:
RewardRepository
- Service:
RewardService
Notification Context
- Entity:
Notification
- Attributes:
notificationId
userId
message
type (SpotAvailable, ReservationConfirmed, etc.)
status (Sent, Read)
timestamp
- Aggregate Root:
Notification
- Service:
NotificationService
Mapping Context
- Value Object:
Location
- Attributes:
latitude
longitude
address (optional)
- Service:
MappingService
- Interacts with external APIs to convert between addresses and coordinates.
Domain Services and Interactions
UserService
- Methods:
registerUser()
authenticateUser()
updateUserProfile()
getUserDetails(userId)
calculateUserRating(userId)
ParkingService
- Methods:
reportAvailability(leavingUserId, location, estimatedLeavingTime)
getAvailableSpots(location, radius)
reserveSpot(availabilityId, arrivingUserId)
confirmSpotTaken(availabilityId, arrivingUserId)
cancelAvailability(availabilityId, userId)
handleNoShow(reservationId)
RewardService
- Methods:
calculateReward(availabilityId, reservationId)
- The amount can be variable based on factors like demand, location, time.
processReward(rewardId)
handleFailedReward(rewardId)
NotificationService
- Methods:
sendNotification(userId, message, type)
broadcastAvailability(availabilityId, location)
notifyReservationStatus(reservationId)
MappingService
- Methods:
getCoordinates(address)
getAddress(latitude, longitude)
calculateDistance(location1, location2)
Domain Events
-
SpotAvailableEvent
- Triggered when a leaving user reports availability.
- Handled by
NotificationService to alert nearby users.
-
SpotReservedEvent
- Triggered when an arriving user reserves a spot.
- Updates the status in
ParkingService and notifies the leaving user.
-
SpotTakenEvent
- Triggered when the arriving user confirms they've taken the spot.
- Initiates reward processing in
RewardService.
-
ReservationCanceledEvent
- Triggered when a reservation is canceled.
- Frees up the availability for other users.
-
NoShowEvent
- Triggered when the arriving user fails to show up.
- May impact user ratings and handle potential penalties.
Workflow Scenarios
1. Leaving User Reports Availability
- Action:
- Leaving user opens the app and signals they are leaving a spot.
- Provides estimated leaving time and confirms location.
- Process:
ParkingService.reportAvailability() creates a new Availability with status Available.
SpotAvailableEvent is triggered.
- Outcome:
NotificationService broadcasts the availability to nearby users.
2. Arriving User Searches and Reserves a Spot
- Action:
- Arriving user searches for available spots within a radius.
- Process:
ParkingService.getAvailableSpots() returns a list of Availability instances.
- User selects a spot and calls
ParkingService.reserveSpot().
- Status of
Availability changes to Reserved, and reservedByUserId is set.
SpotReservedEvent is triggered.
- Outcome:
NotificationService notifies the leaving user of the reservation.
- The spot is marked as reserved for a specific time window.
3. Arriving User Confirms Spot Taken
- Action:
- Arriving user reaches the spot and confirms it's taken via
ParkingService.confirmSpotTaken().
- Process:
- Status of
Availability changes to Taken.
SpotTakenEvent is triggered.
- Outcome:
RewardService.calculateReward() determines the reward amount.
RewardService.processReward() handles payment to the leaving user.
NotificationService updates both users about the successful transaction.
4. Handling Cancellations or No-Shows
- Cancellation:
- User cancels via
ParkingService.cancelAvailability() or ParkingService.cancelReservation().
- Status changes accordingly, and
ReservationCanceledEvent is triggered.
- No-Show:
- If the arriving user doesn't confirm within a time window,
NoShowEvent is triggered.
ParkingService updates status, and UserService may adjust user ratings.
Data Model Examples
User Entity
public class User {
private UUID userId;
private String name;
private String email;
private String phoneNumber;
private PaymentInfo paymentInfo;
private double rating;
// Getters and setters omitted for brevity
}
Availability Entity
public class Availability {
private UUID availabilityId;
private UUID leavingUserId;
private Location location;
private LocalDateTime estimatedLeavingTime;
private AvailabilityStatus status;
private UUID reservedByUserId;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
// Getters and setters omitted for brevity
}
Reward Entity
public class Reward {
private UUID rewardId;
private UUID fromUserId;
private UUID toUserId;
private BigDecimal amount;
private RewardStatus status;
private LocalDateTime timestamp;
// Getters and setters omitted for brevity
}
Technical Considerations
- Concurrency and Consistency:
- Use optimistic locking or transactions to handle concurrent reservations.
- Scalability:
- Implement caching strategies for frequently accessed data.
- Use asynchronous messaging (e.g., RabbitMQ, Kafka) for events.
- Security:
- Implement authentication and authorization (e.g., JWT tokens).
- Secure sensitive data like payment info.
- Performance:
- Optimize database queries.
- Use indexing on location data for efficient searches.
- Reliability:
- Implement retry mechanisms for external service calls.
- Validate data at every layer.
Example Sequence Diagram
Scenario: Arriving user reserves and takes a parking spot.
- Arriving User searches for spots.
- Calls
ParkingService.getAvailableSpots().
- Receives available spots list.
- Selects one and calls
ParkingService.reserveSpot().
ParkingService updates the Availability status.
SpotReservedEvent is triggered.
NotificationService notifies the leaving user.
- Arriving user goes to the spot and calls
ParkingService.confirmSpotTaken().
ParkingService updates the status to Taken.
SpotTakenEvent is triggered.
RewardService processes the reward.
NotificationService notifies both users of the successful transaction.
Conclusion
By following DDD principles, we've structured the parking spot exchange application into clear bounded contexts, each managing its specific domain logic. Entities, value objects, aggregates, and domain events are defined to encapsulate the business rules and workflows.
This modular design promotes scalability, maintainability, and a clear separation of concerns, which are essential for the complex interactions in an application akin to Uber but for parking spots.
Next Steps:
- Prototyping: Begin implementing the core services, starting with the
UserService and ParkingService.
- Integration: Set up the infrastructure for domain events and ensure services can communicate effectively.
- Testing: Write unit and integration tests for each service.
- Feedback Loop: Continuously gather user feedback to refine the reward system and user experience.
Feel free to ask if you need more detailed explanations on any of the components or further assistance with the implementation strategy.