10106 . [ 주요 패턴] ( #주요-패턴 )
11117 . [ 데이터 흐름] ( #데이터-흐름 )
1212
13+ > 📖 ** 의존성 규칙 상세 가이드** : [ DEPENDENCY_RULES.md] ( ./DEPENDENCY_RULES.md ) 를 참조하세요.
14+
1315---
1416
1517## 아키텍처 개요
@@ -246,7 +248,21 @@ src/beanllm/
246248│ │ ├── __init__.py
247249│ │ └── model_scanner.py # ModelScanner
248250│ │
249- │ └── ml/ # ML Models
251+ │ ├── security/ # Security
252+ │ │ ├── __init__.py
253+ │ │ └── config.py # SecureConfig
254+ │ │
255+ │ └── integrations/ # 외부 프레임워크 통합
256+ │ ├── __init__.py
257+ │ ├── README.md # 통합 가이드
258+ │ ├── langgraph/ # LangGraph 통합
259+ │ │ ├── bridge.py # beanLLM ↔ LangGraph 변환
260+ │ │ └── workflow.py # LangGraph 워크플로우 빌더
261+ │ └── llamaindex/ # LlamaIndex 통합
262+ │ ├── bridge.py # beanLLM ↔ LlamaIndex 변환
263+ │ └── query_engine.py # LlamaIndex Query Engine 래퍼
264+ │
265+ │ └── ml/ # ML Models (미사용)
250266│ ├── __init__.py
251267│ └── ml_models.py # BaseMLModel, PyTorchModel 등
252268│
@@ -285,15 +301,116 @@ src/beanllm/
285301
286302## 의존성 방향
287303
304+ 자세한 내용은 [ DEPENDENCY_RULES.md] ( ./DEPENDENCY_RULES.md ) 를 참고하세요.
305+
306+ ## 분산 아키텍처
307+
308+ ### 개요
309+
310+ 환경변수 ` USE_DISTRIBUTED ` 에 따라 분산/인메모리 모드를 자동 선택하는 추상화 레이어를 제공합니다.
311+
312+ - ** 인메모리 모드** (` USE_DISTRIBUTED=false ` ): 기존 코드와 동일하게 동작
313+ - ** 분산 모드** (` USE_DISTRIBUTED=true ` ): Redis/Kafka를 사용한 분산 처리
314+
315+ ### 주요 컴포넌트
316+
317+ 1 . ** Rate Limiting** : Redis 기반 분산 Rate Limiter
318+ 2 . ** 캐싱** : Redis 기반 분산 캐시
319+ 3 . ** 작업 큐** : Kafka 기반 작업 큐
320+ 4 . ** 이벤트 스트리밍** : Kafka 기반 이벤트 발행/구독
321+ 5 . ** 분산 락** : Redis 기반 분산 락
322+
323+ ### 데코레이터 패턴
324+
325+ 분산 시스템 기능을 자동으로 적용하는 데코레이터를 제공하여 코드 중복을 85-90% 감소시켰습니다.
326+
327+ ``` python
328+ from beanllm.infrastructure.distributed import with_distributed_features
329+
330+ @with_distributed_features (
331+ pipeline_type = " vision_rag" ,
332+ enable_cache = True ,
333+ enable_rate_limiting = True ,
334+ enable_event_streaming = True ,
335+ cache_key_prefix = " vision_rag:retrieve" ,
336+ rate_limit_key = " vision:embedding" ,
337+ event_type = " vision_rag.retrieve" ,
338+ )
339+ async def retrieve (self , request : VisionRAGRequest) -> VisionRAGResponse:
340+ # 실제 로직만 작성 (캐싱, Rate Limiting, 이벤트 스트리밍 자동 적용)
341+ results = self ._vector_store.similarity_search(query, k = k)
342+ return VisionRAGResponse(results = results)
343+ ```
344+
345+ ** 자동 적용 기능:**
346+ - ✅ 캐싱 (자동 키 생성, 조회, 저장)
347+ - ✅ Rate Limiting (설정 기반)
348+ - ✅ 이벤트 스트리밍 (시작/완료/실패)
349+ - ✅ 분산 락 (파일 경로 기반 자동 감지)
350+ - ✅ 동기/비동기 자동 감지
351+
352+ ### 동적 설정 변경
353+
354+ 런타임에 파이프라인별 설정을 자유롭게 수정할 수 있습니다.
355+
356+ ``` python
357+ from beanllm.infrastructure.distributed import update_pipeline_config
358+
359+ # Vision RAG의 Rate Limiting 비활성화
360+ update_pipeline_config(" vision_rag" , enable_rate_limiting = False )
361+
362+ # Chain의 캐시 TTL 변경
363+ update_pipeline_config(" chain" , chain_cache_ttl = 7200 )
364+
365+ # Multi-Agent의 Kafka Bus 활성화
366+ update_pipeline_config(" multi_agent" , use_kafka_bus = True )
367+ ```
368+
369+ ### 사용법
370+
371+ ``` python
372+ from beanllm.infrastructure.distributed import (
373+ get_rate_limiter,
374+ get_cache,
375+ get_task_queue,
376+ get_event_bus,
377+ get_distributed_lock,
378+ update_pipeline_config,
379+ get_pipeline_config
380+ )
381+
382+ # 환경변수로 자동 선택
383+ rate_limiter = get_rate_limiter()
384+ cache = get_cache()
385+ task_queue = get_task_queue(" ocr.tasks" )
386+ producer, consumer = get_event_bus()
387+ lock = get_distributed_lock()
388+
389+ # 설정 조회 및 수정
390+ config = get_pipeline_config(" vision_rag" )
391+ update_pipeline_config(" vision_rag" , enable_cache = True , cache_ttl = 3600 )
392+ ```
393+
394+ ** 참고 자료:**
395+ - 상세 가이드: [ src/beanllm/infrastructure/distributed/README.md] ( ./src/beanllm/infrastructure/distributed/README.md )
396+ - 성능 가이드: [ docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md] ( ./docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md )
397+
398+ ---
399+
400+ ## 의존성 방향
401+
402+ > 📖 ** 상세 가이드** : [ DEPENDENCY_RULES.md] ( ./DEPENDENCY_RULES.md ) 를 참조하세요.
403+
288404### 원칙
289405
2904061 . ** 의존성은 항상 안쪽으로** (Dependency Rule)
291407 - Facade → Handler → Service → Domain ← Infrastructure
292408 - Domain은 어떤 레이어에도 의존하지 않음
293409
294- 2 . ** 인터페이스에 의존**
295- - Service는 인터페이스(IChatService)에 의존
296- - 구현체(ChatServiceImpl)는 Infrastructure에 위치
410+ 2 . ** 인터페이스에 의존** (Dependency Inversion Principle)
411+ - Handler는 Service 인터페이스(IChatService)에 의존
412+ - Service는 Domain 인터페이스에 의존
413+ - Infrastructure는 Domain 인터페이스를 구현
297414
2984153 . ** 의존성 주입 (Dependency Injection)**
299416 - Factory 패턴으로 의존성 관리
@@ -302,15 +419,53 @@ src/beanllm/
302419### 의존성 다이어그램
303420
304421```
305- Facade Layer
306- ↓ (의존)
307- Handler Layer
308- ↓ (의존)
309- Service Layer (인터페이스)
310- ↓ (의존)
311- Domain Layer ← Infrastructure Layer (구현체)
422+ ┌─────────────────────────────────────────────────────────┐
423+ │ Facade Layer │
424+ │ ✅ Handler, DTO, Utils, Domain/Infrastructure │
425+ │ ❌ Service (구현체) │
426+ └──────────────────────┬────────────────────────────────────┘
427+ │ 의존
428+ ┌──────────────────────▼────────────────────────────────────┐
429+ │ Handler Layer │
430+ │ ✅ Service (인터페이스), DTO, Utils │
431+ │ ❌ Service (구현체), Domain, Infrastructure │
432+ └──────────────────────┬────────────────────────────────────┘
433+ │ 의존
434+ ┌──────────────────────▼────────────────────────────────────┐
435+ │ Service Layer │
436+ │ ✅ Domain (인터페이스), Infrastructure (인터페이스) │
437+ │ ❌ Handler, Facade │
438+ └──────────────────────┬────────────────────────────────────┘
439+ │ 의존
440+ ┌──────────────────────▼────────────────────────────────────┐
441+ │ Domain Layer │
442+ │ ✅ Domain 내부 모듈만 │
443+ │ ❌ Service, Handler, Facade, Infrastructure │
444+ └──────────────────────┬────────────────────────────────────┘
445+ │ 구현
446+ ┌──────────────────────▼────────────────────────────────────┐
447+ │ Infrastructure Layer │
448+ │ ✅ Domain (인터페이스), Utils │
449+ │ ❌ Service, Handler, Facade │
450+ └───────────────────────────────────────────────────────────┘
312451```
313452
453+ ### 핵심 규칙 요약
454+
455+ ** 허용된 의존성:**
456+ - ✅ ** Facade** → Handler, DTO, Utils, Domain/Infrastructure (직접 사용 가능)
457+ - ✅ ** Handler** → Service (인터페이스), DTO, Utils
458+ - ✅ ** Service** → Domain (인터페이스), Infrastructure (인터페이스), DTO
459+ - ✅ ** Domain** → Domain 내부만
460+ - ✅ ** Infrastructure** → Domain (인터페이스), Utils
461+
462+ ** 금지된 의존성:**
463+ - ❌ 순환 의존 (Circular Dependency)
464+ - ❌ 역방향 의존 (하위 레이어 → 상위 레이어)
465+ - ❌ 구현체 직접 의존 (인터페이스 사용 필수)
466+ - ❌ Handler/Facade → Service 구현체
467+ - ❌ Domain → Service/Handler/Facade
468+
314469---
315470
316471## 설계 원칙
@@ -538,6 +693,16 @@ from beanllm.facade import Client, RAGChain, Agent
538693- 모든 LLM 호출은 async/await
539694- Streaming 지원
540695
696+ ### 4. 대용량 처리
697+ - ** 스트리밍** : LLM 응답, 파일 로딩 스트리밍 지원
698+ - ** 메모리 매핑 (mmap)** : 10MB 이상 파일 자동 mmap 사용
699+ - ** 배치 처리** : Embedding 배치 처리, 동적 배치 분할
700+ - ** 병렬 처리** : ProcessPoolExecutor, asyncio.gather() 활용
701+ - ** 지연 로딩** : LazyLoadMixin으로 필요 시 로드
702+ - ** 캐싱** : LRU Cache로 메모리 효율성 향상
703+ - ** 분산 아키텍처** : Redis/Kafka 기반 분산 처리 (선택적)
704+ - 자세한 내용: [ docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md] ( ./docs/DISTRIBUTED_ARCHITECTURE_PERFORMANCE.md )
705+
541706---
542707
543708## 보안 고려사항
@@ -580,4 +745,4 @@ response = client.chat("Hello")
580745
581746---
582747
583- ** 최종 업데이트** : 2025-12-22
748+ ** 최종 업데이트** : 2026-01-XX
0 commit comments