Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

Which the best architecture for module in pure java backend service?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    Which the best architecture for module in pure java backend service?

  2. Claude Assistant

    For pure Java backend services, the choice of architecture depends on your specific requirements, but I'll outline the most effective patterns and principles commonly used in modern Java applications.

    Layered Architecture with Domain-Driven Design is often the most practical starting point for many Java backend services. This approach organizes your code into distinct layers: presentation/API layer (REST controllers or GraphQL resolvers), application/service layer (business logic orchestration), domain layer (core business rules and entities), and infrastructure layer (database access, external service integrations). This separation provides clear boundaries and makes the codebase easier to understand and maintain.

    Hexagonal Architecture (Ports and Adapters) takes this further by making your core business logic completely independent of external concerns. Your domain logic sits at the center, with ports defining interfaces for what the application needs, and adapters implementing those interfaces for specific technologies. This makes your application highly testable and flexible to technology changes.

    For larger, more complex systems, Modular Monolith architecture can be excellent before jumping to microservices. You structure your application as separate modules within a single deployable unit, with clear boundaries between modules. Each module can have its own internal layered architecture, and modules communicate through well-defined interfaces. This gives you many benefits of microservices (like team autonomy and clear boundaries) without the operational complexity.

    Event-Driven Architecture works well when you need loose coupling between components and asynchronous processing. Using frameworks like Spring's application events or more robust solutions like Apache Kafka, you can build systems where modules communicate through events rather than direct method calls.

    Key principles to follow regardless of the specific pattern include: dependency inversion (depend on abstractions, not concrete implementations), single responsibility (each class/module should have one reason to change), and explicit boundaries between modules. Use dependency injection frameworks like Spring to manage component wiring, and consider using Java modules (JPMS) for enforcing architectural boundaries at compile time.

    For most Java backend services, I'd recommend starting with a well-structured layered architecture using Spring Boot, organizing code by feature rather than technical layers, and keeping the option open to evolve toward hexagonal architecture or a modular monolith as complexity grows. This provides a good balance of simplicity, maintainability, and flexibility for future changes.

  3. User

    Please, give me simple examples

  4. Claude Assistant

    Here are simple examples of the main architectural patterns:

    1. Layered Architecture

    // Controller Layer
    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        private final UserService userService;
        
        @PostMapping
        public ResponseEntity<UserDto> createUser(@RequestBody CreateUserRequest request) {
            User user = userService.createUser(request.getName(), request.getEmail());
            return ResponseEntity.ok(UserDto.from(user));
        }
    }
    
    // Service Layer
    @Service
    public class UserService {
        private final UserRepository userRepository;
        private final EmailService emailService;
        
        @Transactional
        public User createUser(String name, String email) {
            // Business logic
            if (userRepository.existsByEmail(email)) {
                throw new DuplicateEmailException("Email already exists");
            }
            
            User user = new User(name, email);
            user = userRepository.save(user);
            emailService.sendWelcomeEmail(user);
            return user;
        }
    }
    
    // Repository Layer
    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {
        boolean existsByEmail(String email);
    }
    
    // Domain Model
    @Entity
    public class User {
        @Id
        @GeneratedValue
        private Long id;
        private String name;
        private String email;
        
        // constructors, getters, setters
    }
    

    2. Hexagonal Architecture (Ports and Adapters)

    // Core Domain (inside hexagon)
    public class User {
        private final UserId id;
        private final String name;
        private final String email;
        
        public User(String name, String email) {
            this.id = UserId.generate();
            this.name = name;
            this.email = email;
        }
    }
    
    // Port (interface defined by domain)
    public interface UserRepository {
        User save(User user);
        Optional<User> findByEmail(String email);
    }
    
    // Port (for sending notifications)
    public interface NotificationService {
        void sendWelcomeNotification(User user);
    }
    
    // Use Case (application service)
    public class CreateUserUseCase {
        private final UserRepository userRepository;
        private final NotificationService notificationService;
        
        public User execute(String name, String email) {
            if (userRepository.findByEmail(email).isPresent()) {
                throw new DuplicateEmailException();
            }
            
            User user = new User(name, email);
            user = userRepository.save(user);
            notificationService.sendWelcomeNotification(user);
            return user;
        }
    }
    
    // Adapter (infrastructure - implements port)
    @Component
    public class JpaUserRepository implements UserRepository {
        private final SpringDataUserRepository springRepo;
        
        @Override
        public User save(User user) {
            UserEntity entity = toEntity(user);
            entity = springRepo.save(entity);
            return toDomain(entity);
        }
    }
    
    // Adapter (REST controller)
    @RestController
    public class UserRestAdapter {
        private final CreateUserUseCase createUserUseCase;
        
        @PostMapping("/users")
        public UserResponse createUser(@RequestBody CreateUserRequest request) {
            User user = createUserUseCase.execute(request.name(), request.email());
            return new UserResponse(user.getId(), user.getName(), user.getEmail());
        }
    }
    

    3. Modular Monolith

    // user-module/src/main/java/com/app/user/api/UserApi.java
    public interface UserApi {
        UserDto createUser(CreateUserCommand command);
        Optional<UserDto> findUser(Long userId);
    }
    
    // user-module/src/main/java/com/app/user/internal/UserService.java
    @Service
    class UserService implements UserApi {
        private final UserRepository repository;
        
        @Override
        public UserDto createUser(CreateUserCommand command) {
            User user = new User(command.name(), command.email());
            user = repository.save(user);
            return UserDto.from(user);
        }
    }
    
    // order-module/src/main/java/com/app/order/internal/OrderService.java
    @Service
    class OrderService {
        private final UserApi userApi;  // Depends only on interface
        private final OrderRepository orderRepository;
        
        public Order createOrder(Long userId, List<OrderItem> items) {
            // Call user module through API
            UserDto user = userApi.findUser(userId)
                .orElseThrow(() -> new UserNotFoundException());
            
            Order order = new Order(userId, items);
            return orderRepository.save(order);
        }
    }
    
    // Module configuration
    @Configuration
    @ComponentScan("com.app.user.internal")
    public class UserModuleConfig {
        // Module-specific beans
    }
    

    4. Event-Driven Architecture

    // Event
    public class UserCreatedEvent {
        private final Long userId;
        private final String email;
        private final Instant timestamp;
        
        // constructor, getters
    }
    
    // Event Publisher
    @Service
    public class UserService {
        private final ApplicationEventPublisher eventPublisher;
        
        @Transactional
        public User createUser(String name, String email) {
            User user = new User(name, email);
            user = userRepository.save(user);
            
            // Publish event
            eventPublisher.publishEvent(
                new UserCreatedEvent(user.getId(), user.getEmail(), Instant.now())
            );
            
            return user;
        }
    }
    
    // Event Listeners
    @Component
    public class EmailNotificationListener {
        @EventListener
        @Async
        public void handleUserCreated(UserCreatedEvent event) {
            // Send welcome email
            sendEmail(event.getEmail(), "Welcome!");
        }
    }
    
    @Component
    public class AuditListener {
        @EventListener
        public void handleUserCreated(UserCreatedEvent event) {
            // Log audit entry
            auditLog.record("User created: " + event.getUserId());
        }
    }
    

    Simple Project Structure Example

    my-service/
    ├── src/main/java/com/myapp/
    │   ├── user/                    # Feature-based organization
    │   │   ├── api/
    │   │   │   └── UserController.java
    │   │   ├── domain/
    │   │   │   ├── User.java
    │   │   │   └── UserRepository.java
    │   │   ├── service/
    │   │   │   └── UserService.java
    │   │   └── infrastructure/
    │   │       └── JpaUserRepository.java
    │   ├── order/                   # Another feature
    │   │   ├── api/
    │   │   ├── domain/
    │   │   └── service/
    │   └── shared/                  # Shared utilities
    │       └── exception/
    └── src/test/java/
    

    Each pattern has its place - start with simple layered architecture and evolve as your needs grow!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.