<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by İlayda ŞAHİN on Medium]]></title>
        <description><![CDATA[Stories by İlayda ŞAHİN on Medium]]></description>
        <link>https://medium.com/@sahin.ilyd?source=rss-34bcb7b93442------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VI-0EqRBWIIaAm8tBSqLDg.jpeg</url>
            <title>Stories by İlayda ŞAHİN on Medium</title>
            <link>https://medium.com/@sahin.ilyd?source=rss-34bcb7b93442------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:14:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sahin.ilyd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Veritabanına Yazdın. Event’i Publish Ettin. İkisinden Biri Yalan Söyledi.]]></title>
            <link>https://medium.com/@sahin.ilyd/veritaban%C4%B1na-yazd%C4%B1n-eventi-publish-ettin-i%CC%87kisinden-biri-yalan-s%C3%B6yledi-166ab67eb5f9?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/166ab67eb5f9</guid>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 12:39:53 GMT</pubDate>
            <atom:updated>2026-04-06T12:39:53.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot + React’ta Transactional Outbox Pattern</h3><p><em>Stack: Spring Boot 3.x · Spring Data JPA · PostgreSQL · Kafka (veya RabbitMQ) · React 18</em></p><p>Bir class bug vardır: unit test’te çıkmaz, staging’i geçer, production’da patlayar. Yük altında, ağ titrediğinde veya bir deploy’un hemen ardından.</p><p>Bu onlardan biri.</p><h3>Sahne</h3><p>Bir e-ticaret sistemi kuruyorsun. Kullanıcı sipariş veriyor. İki şey olmalı:</p><ol><li>Sipariş veritabanına kaydedilmeli.</li><li>OrderPlaced event&#39;i Kafka&#39;ya gönderilmeli — envanter servisi, bildirim servisi ve depo bu event&#39;e göre hareket edecek.</li></ol><p>Çoğu developer şunu yazar:</p><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final OrderRepository orderRepository;<br>    private final KafkaTemplate&lt;String, OrderPlacedEvent&gt; kafkaTemplate;</pre><pre>    @Transactional<br>    public Order placeOrder(PlaceOrderRequest request) {<br>        Order order = Order.builder()<br>            .userId(request.getUserId())<br>            .totalAmount(request.getTotalAmount())<br>            .status(OrderStatus.PENDING)<br>            .build();</pre><pre>        Order saved = orderRepository.save(order);</pre><pre>        // Kayıt sonrası event gönder<br>        kafkaTemplate.send(&quot;order-placed&quot;, new OrderPlacedEvent(saved.getId()));</pre><pre>        return saved;<br>    }<br>}</pre><p>Makul görünüyor. Çoğu zaman da çalışıyor.</p><h3>Nerede Kopuyor</h3><p>Akışı takip edelim:</p><ol><li>Transaction açıldı.</li><li>ORDER satırı insert edildi (henüz commit olmadı).</li><li>kafkaTemplate.send() tetiklendi — mesaj Kafka&#39;ya düştü.</li><li>Transaction commit oldu.</li></ol><p>Şimdi 4. adım başarısız olsun. Deadlock. Constraint violation. Timeout. Transaction rollback oldu. Satır hiç yazılmadı.</p><p>Ama Kafka mesajı artık dışarıda. Envanter servisi stoğu düşürdü. Depo bir pick görevi oluşturdu. Bildirim servisi onay maili gönderdi.</p><p><strong>Veritabanın siparişin var olmadığını söylüyor. Downstream sistemlerin var olduğunu düşünüyor.</strong></p><p>Tersi de bir o kadar acı: commit başarılı ama mesaj publish edilemedi. Sipariş DB’de duruyor ama downstream’deki hiçbir servis haberdar değil.</p><p>Bu <strong>dual-write problemi</strong>. İki sistem, bir mantıksal işlem, aralarında atomicity yok.</p><h3>Neden @TransactionalEventListener Tam Çözmüyor</h3><p>Spring’in @TransactionalEventListener&#39;ı event&#39;i commit sonrasına erteliyor:</p><pre>@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)<br>public void handleOrderPlaced(OrderPlacedEvent event) {<br>    kafkaTemplate.send(&quot;order-placed&quot;, event);<br>}</pre><p>Rollback sorununu çözüyor — transaction rollback olursa event tetiklenmiyor. Daha iyi.</p><p>Ama commit ile event publication arasında uygulama crash olursa? Kafka o an erişilemez durumdaysa? Commit başarılı, event kayboldu ve retry mekanizman yok. Bir hata modunu başka biriyle değiştirdin.</p><h3>Outbox Pattern</h3><p>Çözüm aldatıcı derecede basit: <strong>event yayınlamayı bir veritabanı işlemi olarak ele al</strong>.</p><p>Kafka’ya direkt yazmak yerine, event’i bir outbox tablosuna yaz — iş verine ile aynı transaction içinde. Ayrı bir process (&quot;relay&quot;) outbox tablosunu okur ve mesajları Kafka&#39;ya iletir. Kaydı sadece başarılı teslimden sonra siler veya işaretler.</p><pre>┌─────────────────────────────────────────┐<br>│           Senin Transaction&#39;ın          │<br>│                                         │<br>│  INSERT INTO orders (...)               │<br>│  INSERT INTO outbox (event_type, ...)   │<br>│                                         │<br>│  ← ikisi birlikte commit, ya da hiçbiri │<br>└─────────────────────────────────────────┘<br>           │<br>           │ (ayrı bir process)<br>           ▼<br>┌─────────────────────────────────────────┐<br>│           Outbox Relay                  │<br>│                                         │<br>│  SELECT * FROM outbox WHERE sent = false│<br>│  → Kafka&#39;ya publish et                  │<br>│  → sent olarak işaretle (veya sil)      │<br>└─────────────────────────────────────────┘</pre><p>Veritabanı hem domain datanın hem de bekleyen event’lerin tek kayıt kaynağı oluyor. Artık distributed koordinasyon gerekmez — sadece local bir transaction.</p><h3>İmplementasyon</h3><h3>1. Outbox Tablosu</h3><pre>CREATE TABLE outbox_events (<br>    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>    event_type  VARCHAR(255) NOT NULL,<br>    aggregate_id VARCHAR(255) NOT NULL,<br>    payload     JSONB NOT NULL,<br>    created_at  TIMESTAMP NOT NULL DEFAULT now(),<br>    sent_at     TIMESTAMP,<br>    retry_count INT NOT NULL DEFAULT 0<br>);</pre><pre>CREATE INDEX idx_outbox_unsent ON outbox_events (created_at)<br>    WHERE sent_at IS NULL;</pre><h3>2. Entity</h3><pre>@Entity<br>@Table(name = &quot;outbox_events&quot;)<br>@Getter<br>@NoArgsConstructor<br>public class OutboxEvent {</pre><pre>    @Id<br>    @GeneratedValue<br>    private UUID id;</pre><pre>    @Column(nullable = false)<br>    private String eventType;</pre><pre>    @Column(nullable = false)<br>    private String aggregateId;</pre><pre>    @Column(columnDefinition = &quot;jsonb&quot;, nullable = false)<br>    private String payload;</pre><pre>    @Column(nullable = false)<br>    private LocalDateTime createdAt = LocalDateTime.now();</pre><pre>    private LocalDateTime sentAt;</pre><pre>    private int retryCount = 0;</pre><pre>    public static OutboxEvent of(String eventType, String aggregateId, Object payload) {<br>        OutboxEvent event = new OutboxEvent();<br>        event.eventType = eventType;<br>        event.aggregateId = aggregateId;<br>        event.payload = serialize(payload);<br>        return event;<br>    }</pre><pre>    public void markAsSent() {<br>        this.sentAt = LocalDateTime.now();<br>    }</pre><pre>    public void incrementRetry() {<br>        this.retryCount++;<br>    }</pre><pre>    private static String serialize(Object obj) {<br>        try {<br>            return new ObjectMapper().writeValueAsString(obj);<br>        } catch (JsonProcessingException e) {<br>            throw new IllegalArgumentException(&quot;Event payload serialize edilemedi&quot;, e);<br>        }<br>    }<br>}</pre><h3>3. Repository</h3><pre>public interface OutboxEventRepository extends JpaRepository&lt;OutboxEvent, UUID&gt; {</pre><pre>    @Lock(LockModeType.PESSIMISTIC_WRITE)<br>    @Query(&quot;&quot;&quot;<br>        SELECT e FROM OutboxEvent e<br>        WHERE e.sentAt IS NULL<br>        ORDER BY e.createdAt ASC<br>        LIMIT :limit<br>    &quot;&quot;&quot;)<br>    List&lt;OutboxEvent&gt; findUnsentEvents(@Param(&quot;limit&quot;) int limit);<br>}</pre><blockquote><em>Pessimistic lock burada kritik. Birden fazla uygulama instance’ı çalışıyorsa (ve çalışıyordur), iki relay thread’i aynı event’i aynı anda almamalı. Birazdan buna döneceğiz.</em></blockquote><h3>4. Outbox’a Yazmak (Transaction İçinde)</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final OrderRepository orderRepository;<br>    private final OutboxEventRepository outboxEventRepository;</pre><pre>    @Transactional<br>    public Order placeOrder(PlaceOrderRequest request) {<br>        Order order = Order.builder()<br>            .userId(request.getUserId())<br>            .totalAmount(request.getTotalAmount())<br>            .status(OrderStatus.PENDING)<br>            .build();</pre><pre>        Order saved = orderRepository.save(order);</pre><pre>        // Burada Kafka yok. Outbox&#39;a yazıyoruz.<br>        OutboxEvent outboxEvent = OutboxEvent.of(<br>            &quot;ORDER_PLACED&quot;,<br>            saved.getId().toString(),<br>            new OrderPlacedEvent(saved.getId(), saved.getUserId(), saved.getTotalAmount())<br>        );<br>        outboxEventRepository.save(outboxEvent);</pre><pre>        return saved;<br>    }<br>}</pre><p>OrderService artık Kafka&#39;dan habersiz. Sadece iki tabloya yazıyor. Transaction başarısız olursa her iki yazma da geri alınır. Temiz.</p><h3>5. Outbox Relay</h3><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class OutboxRelayService {</pre><pre>    private static final int BATCH_SIZE = 50;<br>    private static final int MAX_RETRIES = 5;</pre><pre>    private final OutboxEventRepository outboxEventRepository;<br>    private final KafkaTemplate&lt;String, String&gt; kafkaTemplate;</pre><pre>    @Scheduled(fixedDelay = 1000) // her saniye<br>    @Transactional<br>    public void relay() {<br>        List&lt;OutboxEvent&gt; events = outboxEventRepository.findUnsentEvents(BATCH_SIZE);</pre><pre>        for (OutboxEvent event : events) {<br>            try {<br>                String topic = resolveTopicFor(event.getEventType());</pre><pre>                kafkaTemplate.send(topic, event.getAggregateId(), event.getPayload())<br>                    .get(5, TimeUnit.SECONDS); // prod&#39;da callback kullanmayı düşün</pre><pre>                event.markAsSent();</pre><pre>            } catch (Exception ex) {<br>                log.warn(&quot;Outbox event relay başarısız [{}]: {}&quot;, event.getId(), ex.getMessage());<br>                event.incrementRetry();</pre><pre>                if (event.getRetryCount() &gt;= MAX_RETRIES) {<br>                    log.error(&quot;Outbox event [{}] max retry&#39;ı aştı. Dead letter&#39;a taşı.&quot;, event.getId());<br>                    // metrik yay, alert gönder veya dead_letter_outbox tablosuna taşı<br>                }<br>            }<br>        }<br>    }</pre><pre>    private String resolveTopicFor(String eventType) {<br>        return switch (eventType) {<br>            case &quot;ORDER_PLACED&quot;    -&gt; &quot;order-placed&quot;;<br>            case &quot;ORDER_CANCELLED&quot; -&gt; &quot;order-cancelled&quot;;<br>            case &quot;PAYMENT_FAILED&quot;  -&gt; &quot;payment-failed&quot;;<br>            default -&gt; throw new IllegalArgumentException(&quot;Bilinmeyen event tipi: &quot; + eventType);<br>        };<br>    }<br>}</pre><h3>6. Çoklu Instance’da Double Publish Olmadan Çalışmak</h3><p>@Scheduled her instance&#39;da çalışır, yani iki relay aynı event&#39;i alabilir.</p><p><strong>Seçenek A: Veritabanı satır kilidi (yukarıda gösterildi)</strong></p><p>findUnsentEvents&#39;teki PESSIMISTIC_WRITE kilidi, ikinci instance&#39;ı birincisi commit edene kadar bloklar. Düşük throughput&#39;ta yeterli.</p><p><strong>Seçenek B: ShedLock</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;net.javacrumbs.shedlock&lt;/groupId&gt;<br>    &lt;artifactId&gt;shedlock-spring&lt;/artifactId&gt;<br>    &lt;version&gt;5.13.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;net.javacrumbs.shedlock&lt;/groupId&gt;<br>    &lt;artifactId&gt;shedlock-provider-jdbc-template&lt;/artifactId&gt;<br>    &lt;version&gt;5.13.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>@Scheduled(fixedDelay = 1000)<br>@SchedulerLock(name = &quot;outbox_relay&quot;, lockAtMostFor = &quot;PT30S&quot;, lockAtLeastFor = &quot;PT5S&quot;)<br>@Transactional<br>public void relay() {<br>    // Tüm cluster&#39;da aynı anda yalnızca bir instance çalışır<br>}</pre><pre>CREATE TABLE shedlock (<br>    name       VARCHAR(64)  NOT NULL,<br>    lock_until TIMESTAMP    NOT NULL,<br>    locked_at  TIMESTAMP    NOT NULL,<br>    locked_by  VARCHAR(255) NOT NULL,<br>    PRIMARY KEY (name)<br>);</pre><p>ShedLock mevcut veritabanını distributed scheduling için kullanır. Redis yok, Zookeeper yok.</p><h3>React Tarafı: Eventual Consistency’yi UI’a Yansıtmak</h3><p>Asenkron event işleme devreye girince UI’ın bunu yansıtması gerekir. Sipariş “verilmiş” olmak ile “onaylanmış” olmak artık aralarında zaman olan iki farklı durum.</p><h3>Yanlış Yaklaşım</h3><pre>const handlePlaceOrder = async () =&gt; {<br>  await api.post(&#39;/orders&#39;, cart);<br>  navigate(&#39;/orders/confirmation&#39;); // her şeyin bittiğini varsayıyor ✗<br>};</pre><h3>Doğru Yaklaşım</h3><p>Ara durumu açıkça modelleyin:</p><pre>// useOrderStatus.js<br>import { useQuery } from &#39;@tanstack/react-query&#39;;</pre><pre>export function useOrderStatus(orderId) {<br>  return useQuery({<br>    queryKey: [&#39;order-status&#39;, orderId],<br>    queryFn: () =&gt; api.get(`/orders/${orderId}/status`).then(r =&gt; r.data),<br>    refetchInterval: (query) =&gt; {<br>      const terminal = [&#39;CONFIRMED&#39;, &#39;FAILED&#39;, &#39;CANCELLED&#39;];<br>      return terminal.includes(query.state.data?.status) ? false : 2000;<br>    },<br>    enabled: !!orderId,<br>  });<br>}</pre><pre>// OrderConfirmationPage.jsx<br>export default function OrderConfirmationPage() {<br>  const { orderId } = useParams();<br>  const { data: order, isLoading } = useOrderStatus(orderId);</pre><pre>  const statusConfig = {<br>    PENDING:   { label: &#39;Siparişin işleniyor…&#39;,    color: &#39;yellow&#39;, showSpinner: true  },<br>    CONFIRMED: { label: &#39;Sipariş onaylandı!&#39;,       color: &#39;green&#39;,  showSpinner: false },<br>    FAILED:    { label: &#39;Bir sorun oluştu.&#39;,         color: &#39;red&#39;,    showSpinner: false },<br>  };</pre><pre>  if (isLoading) return &lt;Skeleton /&gt;;</pre><pre>  const config = statusConfig[order?.status] ?? statusConfig.PENDING;</pre><pre>  return (<br>    &lt;div className={`status-card status-card--${config.color}`}&gt;<br>      {config.showSpinner &amp;&amp; &lt;Spinner /&gt;}<br>      &lt;p&gt;{config.label}&lt;/p&gt;<br>      {order?.status === &#39;CONFIRMED&#39; &amp;&amp; (<br>        &lt;p&gt;Sipariş #{order.id} · Tahmini teslimat: {order.estimatedDelivery}&lt;/p&gt;<br>      )}<br>      {order?.status === &#39;FAILED&#39; &amp;&amp; (<br>        &lt;button onClick={() =&gt; navigate(&#39;/cart&#39;)}&gt;Tekrar Dene&lt;/button&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Backend’deki sipariş durumu endpoint’i ucuz — sadece bir satır okuyor:</p><pre>@GetMapping(&quot;/orders/{id}/status&quot;)<br>public ResponseEntity&lt;OrderStatusResponse&gt; getOrderStatus(@PathVariable UUID id) {<br>    Order order = orderRepository.findById(id)<br>        .orElseThrow(() -&gt; new ResponseStatusException(HttpStatus.NOT_FOUND));</pre><pre>    return ResponseEntity.ok(new OrderStatusResponse(<br>        order.getId(),<br>        order.getStatus(),<br>        order.getEstimatedDelivery()<br>    ));<br>}</pre><p>React Query polling döngüsünü yönetiyor. Durum terminal bir değere ulaşınca polling otomatik duruyor.</p><h3>Production Checklist</h3><p><strong>Monitoring:</strong></p><pre>// Outbox gecikmesini metrik olarak takip et<br>@Scheduled(fixedDelay = 30_000)<br>public void reportOutboxLag() {<br>    long unsentCount = outboxEventRepository.countBySentAtIsNull();<br>    meterRegistry.gauge(&quot;outbox.unsent_events&quot;, unsentCount);</pre><pre>    if (unsentCount &gt; 500) {<br>        log.error(&quot;Outbox lag kritik seviyede: {} bekleyen event&quot;, unsentCount);<br>    }<br>}</pre><p><strong>Temizlik:</strong></p><pre>// 7 günden eski gönderilmiş event&#39;leri sil<br>@Scheduled(cron = &quot;0 0 2 * * *&quot;) // sabah 2<br>@Transactional<br>public void cleanup() {<br>    LocalDateTime cutoff = LocalDateTime.now().minusDays(7);<br>    int deleted = outboxEventRepository.deleteSentEventsBefore(cutoff);<br>    log.info(&quot;Outbox temizliği: {} kayıt silindi&quot;, deleted);<br>}</pre><p><strong>Consumer tarafında idempotency:</strong></p><p>Relay <em>en az bir kez</em> teslimi garanti eder, <em>tam bir kez</em> değil. Downstream consumer’ların duplicate event’leri zararsız biçimde işlemesi gerekir.</p><pre>@KafkaListener(topics = &quot;order-placed&quot;)<br>public void handleOrderPlaced(OrderPlacedEvent event) {<br>    if (processedEventRepository.existsByEventId(event.getEventId())) {<br>        log.debug(&quot;Duplicate event [{}], atlanıyor&quot;, event.getEventId());<br>        return;<br>    }</pre><pre>    inventoryService.reserveStock(event);<br>    processedEventRepository.save(new ProcessedEvent(event.getEventId()));<br>}</pre><h3>Ne Kazanıyorsun</h3><p>Yaklaşım DB rollback güvenli? Kafka down güvenli? App crash güvenli? Duplicate riski @Transactional içinde direkt publish ✓ ✗ ✗ Düşük @TransactionalEventListener ✓ ✗ ✗ Düşük Outbox Pattern ✓ ✓ ✓ Düşük (idempotency ile)</p><p>Outbox pattern sistemi daha basit yapmaz. Bir karmaşıklığı başkasıyla takas eder — artık izlemen gereken bir relay process, bir background tablosu ve frontend’e aktarman gereken eventual consistency var.</p><p>Ama sana çoğu production sisteminin çok ihtiyaç duyduğu bir garantiyi verir: <strong>veri yazılmışsa, karşılık gelen event eninde sonunda teslim edilecek. Güvenilir şekilde. Yazma ile publish arasındaki her şey çökse bile.</strong></p><p>Bu over-engineering değil. Distributed sistemlerin gerçekte ne yaptığına dair sadece bir dürüstlük.</p><p><em>Docker Compose, Kafka ve Testcontainers integration test’leriyle tam çalışan örnek GitHub’da.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=166ab67eb5f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Saved to the DB. You Published the Event. One of Them Lied.]]></title>
            <link>https://medium.com/@sahin.ilyd/you-saved-to-the-db-you-published-the-event-one-of-them-lied-6759f3efccc5?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/6759f3efccc5</guid>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 12:37:52 GMT</pubDate>
            <atom:updated>2026-04-06T12:37:52.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Transactional Outbox Pattern in Spring Boot + React</h3><p><em>Stack: Spring Boot 3.x · Spring Data JPA · PostgreSQL · Kafka (or RabbitMQ) · React 18</em></p><p>There’s a class of bugs that doesn’t show up in unit tests, passes staging, and only reveals itself in production — under load, during a network hiccup, or right after a deploy.</p><p>This is one of them.</p><h3>The Setup</h3><p>You’re building an e-commerce system. A user places an order. Two things must happen:</p><ol><li>The order gets saved to the database.</li><li>An OrderPlaced event gets published to Kafka so the inventory service, notification service, and warehouse can react.</li></ol><p>Here’s what most developers write:</p><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final OrderRepository orderRepository;<br>    private final KafkaTemplate&lt;String, OrderPlacedEvent&gt; kafkaTemplate;</pre><pre>    @Transactional<br>    public Order placeOrder(PlaceOrderRequest request) {<br>        Order order = Order.builder()<br>            .userId(request.getUserId())<br>            .totalAmount(request.getTotalAmount())<br>            .status(OrderStatus.PENDING)<br>            .build();</pre><pre>        Order saved = orderRepository.save(order);</pre><pre>        // Publish the event right after saving<br>        kafkaTemplate.send(&quot;order-placed&quot;, new OrderPlacedEvent(saved.getId()));</pre><pre>        return saved;<br>    }<br>}</pre><p>This looks reasonable. It even works — most of the time.</p><h3>Where It Falls Apart</h3><p>Let’s trace the execution:</p><ol><li>Transaction opens.</li><li>ORDER row is inserted (not yet committed).</li><li>kafkaTemplate.send() fires — the message lands in Kafka.</li><li>Transaction commits.</li></ol><p>Now imagine step 4 fails. A deadlock. A constraint violation. A timeout. The transaction rolls back. The row never existed.</p><p>But the Kafka message is already out there. The inventory service already decremented stock. The warehouse already queued a pick task. The notification service already sent a confirmation email.</p><p><strong>Your database says the order doesn’t exist. Your downstream systems think it does.</strong></p><p>The reverse is equally painful: the message fails to publish after a successful commit. Now the order exists in your DB but nobody downstream ever heard about it.</p><p>This is the <strong>dual-write problem</strong>. Two systems, one logical operation, no atomicity between them.</p><h3>Why @TransactionalEventListener Doesn’t Fully Save You</h3><p>Spring offers @TransactionalEventListener which fires after the transaction commits:</p><pre>@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)<br>public void handleOrderPlaced(OrderPlacedEvent event) {<br>    kafkaTemplate.send(&quot;order-placed&quot;, event);<br>}</pre><p>This solves the rollback problem — the event won’t fire if the transaction rolls back. Better.</p><p>But what if the application crashes between the commit and the event publication? What if Kafka is temporarily unavailable? The commit succeeded, the event is gone, and there’s no retry mechanism. You’ve traded one failure mode for another.</p><h3>The Outbox Pattern</h3><p>The solution is deceptively simple: <strong>treat event publication as a database operation</strong>.</p><p>Instead of publishing directly to Kafka, write the event to an outbox table — inside the same transaction as your business data. A separate process (the &quot;relay&quot;) reads from the outbox and forwards messages to Kafka. It deletes (or marks) the record only after successful delivery.</p><pre>┌─────────────────────────────────────────┐<br>│           Your Transaction              │<br>│                                         │<br>│  INSERT INTO orders (...)               │<br>│  INSERT INTO outbox (event_type, ...)   │<br>│                                         │<br>│  ← both commit atomically, or neither  │<br>└─────────────────────────────────────────┘<br>           │<br>           │ (separate process)<br>           ▼<br>┌─────────────────────────────────────────┐<br>│           Outbox Relay                  │<br>│                                         │<br>│  SELECT * FROM outbox WHERE sent = false│<br>│  → publish to Kafka                     │<br>│  → mark as sent (or delete)             │<br>└─────────────────────────────────────────┘</pre><p>The database becomes the source of truth for both your domain data and your pending events. You no longer need distributed coordination — just a local transaction.</p><h3>Implementation</h3><h3>1. The Outbox Table</h3><pre>CREATE TABLE outbox_events (<br>    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>    event_type  VARCHAR(255) NOT NULL,<br>    aggregate_id VARCHAR(255) NOT NULL,<br>    payload     JSONB NOT NULL,<br>    created_at  TIMESTAMP NOT NULL DEFAULT now(),<br>    sent_at     TIMESTAMP,<br>    retry_count INT NOT NULL DEFAULT 0<br>);</pre><pre>CREATE INDEX idx_outbox_unsent ON outbox_events (created_at)<br>    WHERE sent_at IS NULL;</pre><h3>2. The Entity</h3><pre>@Entity<br>@Table(name = &quot;outbox_events&quot;)<br>@Getter<br>@NoArgsConstructor<br>public class OutboxEvent {</pre><pre>    @Id<br>    @GeneratedValue<br>    private UUID id;</pre><pre>    @Column(nullable = false)<br>    private String eventType;</pre><pre>    @Column(nullable = false)<br>    private String aggregateId;</pre><pre>    @Column(columnDefinition = &quot;jsonb&quot;, nullable = false)<br>    private String payload;</pre><pre>    @Column(nullable = false)<br>    private LocalDateTime createdAt = LocalDateTime.now();</pre><pre>    private LocalDateTime sentAt;</pre><pre>    private int retryCount = 0;</pre><pre>    public static OutboxEvent of(String eventType, String aggregateId, Object payload) {<br>        OutboxEvent event = new OutboxEvent();<br>        event.eventType = eventType;<br>        event.aggregateId = aggregateId;<br>        event.payload = serialize(payload);<br>        return event;<br>    }</pre><pre>    public void markAsSent() {<br>        this.sentAt = LocalDateTime.now();<br>    }</pre><pre>    public void incrementRetry() {<br>        this.retryCount++;<br>    }</pre><pre>    private static String serialize(Object obj) {<br>        try {<br>            return new ObjectMapper().writeValueAsString(obj);<br>        } catch (JsonProcessingException e) {<br>            throw new IllegalArgumentException(&quot;Cannot serialize event payload&quot;, e);<br>        }<br>    }<br>}</pre><h3>3. The Repository</h3><pre>public interface OutboxEventRepository extends JpaRepository&lt;OutboxEvent, UUID&gt; {</pre><pre>    @Lock(LockModeType.PESSIMISTIC_WRITE)<br>    @Query(&quot;&quot;&quot;<br>        SELECT e FROM OutboxEvent e<br>        WHERE e.sentAt IS NULL<br>        ORDER BY e.createdAt ASC<br>        LIMIT :limit<br>    &quot;&quot;&quot;)<br>    List&lt;OutboxEvent&gt; findUnsentEvents(@Param(&quot;limit&quot;) int limit);<br>}</pre><blockquote><em>The pessimistic lock matters here. If you run multiple instances of your application (and you do), two relay threads must not pick up the same event simultaneously. We’ll revisit this.</em></blockquote><h3>4. Writing to the Outbox (Inside Your Transaction)</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final OrderRepository orderRepository;<br>    private final OutboxEventRepository outboxEventRepository;<br>    private final ObjectMapper objectMapper;</pre><pre>    @Transactional<br>    public Order placeOrder(PlaceOrderRequest request) {<br>        Order order = Order.builder()<br>            .userId(request.getUserId())<br>            .totalAmount(request.getTotalAmount())<br>            .status(OrderStatus.PENDING)<br>            .build();</pre><pre>        Order saved = orderRepository.save(order);</pre><pre>        // No Kafka call here. Write to outbox instead.<br>        OutboxEvent outboxEvent = OutboxEvent.of(<br>            &quot;ORDER_PLACED&quot;,<br>            saved.getId().toString(),<br>            new OrderPlacedEvent(saved.getId(), saved.getUserId(), saved.getTotalAmount())<br>        );<br>        outboxEventRepository.save(outboxEvent);</pre><pre>        return saved;<br>    }<br>}</pre><p>OrderService now has zero knowledge of Kafka. It just writes to two tables. If the transaction fails, both writes roll back together. Clean.</p><h3>5. The Outbox Relay</h3><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class OutboxRelayService {</pre><pre>    private static final int BATCH_SIZE = 50;<br>    private static final int MAX_RETRIES = 5;</pre><pre>    private final OutboxEventRepository outboxEventRepository;<br>    private final KafkaTemplate&lt;String, String&gt; kafkaTemplate;</pre><pre>    @Scheduled(fixedDelay = 1000) // every second<br>    @Transactional<br>    public void relay() {<br>        List&lt;OutboxEvent&gt; events = outboxEventRepository.findUnsentEvents(BATCH_SIZE);</pre><pre>        for (OutboxEvent event : events) {<br>            try {<br>                String topic = resolveTopicFor(event.getEventType());</pre><pre>                kafkaTemplate.send(topic, event.getAggregateId(), event.getPayload())<br>                    .get(5, TimeUnit.SECONDS); // blocking for simplicity; use callbacks in prod</pre><pre>                event.markAsSent();</pre><pre>            } catch (Exception ex) {<br>                log.warn(&quot;Failed to relay outbox event [{}]: {}&quot;, event.getId(), ex.getMessage());<br>                event.incrementRetry();</pre><pre>                if (event.getRetryCount() &gt;= MAX_RETRIES) {<br>                    log.error(&quot;Outbox event [{}] exceeded max retries. Moving to dead letter.&quot;, event.getId());<br>                    // emit a metric, alert, or move to a dead_letter_outbox table<br>                }<br>            }<br>        }<br>    }</pre><pre>    private String resolveTopicFor(String eventType) {<br>        return switch (eventType) {<br>            case &quot;ORDER_PLACED&quot;    -&gt; &quot;order-placed&quot;;<br>            case &quot;ORDER_CANCELLED&quot; -&gt; &quot;order-cancelled&quot;;<br>            case &quot;PAYMENT_FAILED&quot;  -&gt; &quot;payment-failed&quot;;<br>            default -&gt; throw new IllegalArgumentException(&quot;Unknown event type: &quot; + eventType);<br>        };<br>    }<br>}</pre><h3>6. Running Multiple Instances Without Double-Publishing</h3><p>With @Scheduled running on every instance, you&#39;ll get race conditions — two relays picking the same unsent event.</p><p><strong>Option A: Database-level row locking (shown above)</strong></p><p>The PESSIMISTIC_WRITE lock on findUnsentEvents will block the second instance until the first commits. Works fine at low throughput.</p><p><strong>Option B: ShedLock</strong></p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;net.javacrumbs.shedlock&lt;/groupId&gt;<br>    &lt;artifactId&gt;shedlock-spring&lt;/artifactId&gt;<br>    &lt;version&gt;5.13.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;net.javacrumbs.shedlock&lt;/groupId&gt;<br>    &lt;artifactId&gt;shedlock-provider-jdbc-template&lt;/artifactId&gt;<br>    &lt;version&gt;5.13.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>@Scheduled(fixedDelay = 1000)<br>@SchedulerLock(name = &quot;outbox_relay&quot;, lockAtMostFor = &quot;PT30S&quot;, lockAtLeastFor = &quot;PT5S&quot;)<br>@Transactional<br>public void relay() {<br>    // Only one instance runs this at a time, cluster-wide<br>}</pre><pre>CREATE TABLE shedlock (<br>    name       VARCHAR(64)  NOT NULL,<br>    lock_until TIMESTAMP    NOT NULL,<br>    locked_at  TIMESTAMP    NOT NULL,<br>    locked_by  VARCHAR(255) NOT NULL,<br>    PRIMARY KEY (name)<br>);</pre><p>ShedLock uses your existing database to coordinate distributed scheduling. No Redis, no Zookeeper required.</p><h3>The React Side: Handling Eventual Consistency</h3><p>When you introduce async event processing, your UI needs to reflect that. An order being “placed” and an order being “confirmed” are now two different states with time between them.</p><h3>The Wrong Way</h3><pre>const handlePlaceOrder = async () =&gt; {<br>  await api.post(&#39;/orders&#39;, cart);<br>  navigate(&#39;/orders/confirmation&#39;); // assumes everything is done ✗<br>};</pre><h3>The Right Way</h3><p>Model the intermediate state explicitly:</p><pre>// useOrderStatus.js<br>import { useQuery } from &#39;@tanstack/react-query&#39;;</pre><pre>export function useOrderStatus(orderId) {<br>  return useQuery({<br>    queryKey: [&#39;order-status&#39;, orderId],<br>    queryFn: () =&gt; api.get(`/orders/${orderId}/status`).then(r =&gt; r.data),<br>    refetchInterval: (query) =&gt; {<br>      const terminal = [&#39;CONFIRMED&#39;, &#39;FAILED&#39;, &#39;CANCELLED&#39;];<br>      return terminal.includes(query.state.data?.status) ? false : 2000;<br>    },<br>    enabled: !!orderId,<br>  });<br>}</pre><pre>// OrderConfirmationPage.jsx<br>export default function OrderConfirmationPage() {<br>  const { orderId } = useParams();<br>  const { data: order, isLoading } = useOrderStatus(orderId);</pre><pre>  const statusConfig = {<br>    PENDING:   { label: &#39;Processing your order…&#39;,   color: &#39;yellow&#39;, showSpinner: true  },<br>    CONFIRMED: { label: &#39;Order confirmed!&#39;,          color: &#39;green&#39;,  showSpinner: false },<br>    FAILED:    { label: &#39;Something went wrong.&#39;,     color: &#39;red&#39;,    showSpinner: false },<br>  };</pre><pre>  if (isLoading) return &lt;Skeleton /&gt;;</pre><pre>  const config = statusConfig[order?.status] ?? statusConfig.PENDING;</pre><pre>  return (<br>    &lt;div className={`status-card status-card--${config.color}`}&gt;<br>      {config.showSpinner &amp;&amp; &lt;Spinner /&gt;}<br>      &lt;p&gt;{config.label}&lt;/p&gt;<br>      {order?.status === &#39;CONFIRMED&#39; &amp;&amp; (<br>        &lt;p&gt;Order #{order.id} · Estimated delivery: {order.estimatedDelivery}&lt;/p&gt;<br>      )}<br>      {order?.status === &#39;FAILED&#39; &amp;&amp; (<br>        &lt;button onClick={() =&gt; navigate(&#39;/cart&#39;)}&gt;Try Again&lt;/button&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The order status endpoint on the backend is cheap — it just reads one row:</p><pre>@GetMapping(&quot;/orders/{id}/status&quot;)<br>public ResponseEntity&lt;OrderStatusResponse&gt; getOrderStatus(@PathVariable UUID id) {<br>    Order order = orderRepository.findById(id)<br>        .orElseThrow(() -&gt; new ResponseStatusException(HttpStatus.NOT_FOUND));</pre><pre>    return ResponseEntity.ok(new OrderStatusResponse(<br>        order.getId(),<br>        order.getStatus(),<br>        order.getEstimatedDelivery()<br>    ));<br>}</pre><p>React Query handles the polling lifecycle. When the status reaches a terminal state, polling stops automatically.</p><h3>Production Checklist</h3><p><strong>Monitoring:</strong></p><pre>// Track outbox lag as a metric<br>@Scheduled(fixedDelay = 30_000)<br>public void reportOutboxLag() {<br>    long unsentCount = outboxEventRepository.countBySentAtIsNull();<br>    meterRegistry.gauge(&quot;outbox.unsent_events&quot;, unsentCount);</pre><pre>    // Alert if lag grows beyond a threshold<br>    if (unsentCount &gt; 500) {<br>        log.error(&quot;Outbox lag critical: {} unsent events&quot;, unsentCount);<br>    }<br>}</pre><p><strong>Cleanup:</strong></p><pre>// Archive or delete sent events older than 7 days<br>@Scheduled(cron = &quot;0 0 2 * * *&quot;) // 2AM daily<br>@Transactional<br>public void cleanup() {<br>    LocalDateTime cutoff = LocalDateTime.now().minusDays(7);<br>    int deleted = outboxEventRepository.deleteSentEventsBefore(cutoff);<br>    log.info(&quot;Outbox cleanup: {} records removed&quot;, deleted);<br>}</pre><p><strong>Idempotency on the consumer side:</strong></p><p>Your downstream consumers should handle duplicate delivery gracefully. The relay guarantees <em>at-least-once</em> delivery, not <em>exactly-once</em>.</p><pre>@KafkaListener(topics = &quot;order-placed&quot;)<br>public void handleOrderPlaced(OrderPlacedEvent event) {<br>    if (processedEventRepository.existsByEventId(event.getEventId())) {<br>        log.debug(&quot;Duplicate event [{}], skipping&quot;, event.getEventId());<br>        return;<br>    }<br>    <br>    inventoryService.reserveStock(event);<br>    processedEventRepository.save(new ProcessedEvent(event.getEventId()));<br>}</pre><h3>What You Actually Gain</h3><p>Approach DB rollback safe? Kafka down safe? App crash safe? Duplicate risk Direct publish in @Transactional ✓ ✗ ✗ Low @TransactionalEventListener ✓ ✗ ✗ Low Outbox Pattern ✓ ✓ ✓ Low (with idempotency)</p><p>The outbox pattern doesn’t make your system simpler. It trades one complexity for another — now you have a relay process, a background table to monitor, and eventual consistency to communicate to your frontend.</p><p>But it gives you something most production systems desperately need: <strong>a guarantee that if data is written, the corresponding event will be delivered. Eventually. Reliably. Even if everything between write and publish falls apart.</strong></p><p>That’s not overengineering. That’s just honesty about what distributed systems actually do.</p><p><em>The full working example with Docker Compose, Kafka, and Testcontainers integration tests is on GitHub.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6759f3efccc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useCallback and useMemo: Most Resources Only Tell You Half the Story]]></title>
            <link>https://medium.com/@sahin.ilyd/usecallback-and-usememo-most-resources-only-tell-you-half-the-story-3c6a5e6ee797?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6a5e6ee797</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 13:45:00 GMT</pubDate>
            <atom:updated>2026-04-02T13:45:00.703Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The difference between optimizing your app and making it look optimized.</em></p><p>In production code reviews, I keep seeing the same two patterns: either these hooks are missing where they’d actually help, or they’re scattered everywhere they don’t belong.</p><pre>const handleClick = useCallback(() =&gt; {<br>  setCount(c =&gt; c + 1);<br>}, []);</pre><p>This code works. Tests pass. But this useCallback is unnecessary — and it&#39;s making the app slightly slower.</p><p>The reason: “useCallback is for performance” gets repeated everywhere. That framing is incomplete. And because it’s incomplete, it gets misapplied constantly.</p><p>Here’s when useCallback and useMemo actually help, when they don&#39;t, and how to tell the difference — with real examples.</p><h3>The foundational misconception: there’s no such thing as a “performance hook”</h3><p>React’s own documentation now states this directly, but most third-party content still repeats the old framing.</p><p>useCallback and useMemo <strong>consume memory</strong>. Every render triggers a dependency comparison. That comparison has a cost. Using these hooks isn&#39;t free optimization — it&#39;s a conscious <strong>trade-off</strong>.</p><p>Use them in the wrong place and the code you thought you were optimizing is actually doing more work than the naive version. If the component is small, renders infrequently, or the computation is trivial — adding these hooks is a <strong>net regression</strong>.</p><p>So when do they actually help?</p><h3>useCallback: Meaningful in exactly two situations</h3><p>useCallback memoizes a function. As long as its dependencies don&#39;t change, it returns the same function reference across renders.</p><p>Referential stability matters in two specific situations.</p><h3>Situation 1: Passing a function as a prop to a React.memo-wrapped child</h3><p>React.memo prevents a component from re-rendering unless its props change. But in JavaScript, two functions are never referentially equal — even if they do exactly the same thing.</p><pre>const fn1 = () =&gt; {};<br>const fn2 = () =&gt; {};<br>console.log(fn1 === fn2); // false — new reference every time</pre><p>So if you’re passing a function to a React.memo component and that function gets recreated on every parent render, React.memo accomplishes nothing. The child re-renders regardless.</p><pre>// We want ChildComponent to re-render only when onAction changes<br>const ChildComponent = React.memo(({ onAction, label }) =&gt; {<br>  console.log(&#39;ChildComponent rendered&#39;);<br>  return &lt;button onClick={onAction}&gt;{label}&lt;/button&gt;;<br>});</pre><pre>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br>  const [theme, setTheme] = useState(&#39;light&#39;);</pre><pre>  // ❌ handleAction is recreated whenever theme changes<br>  // React.memo can&#39;t detect the difference — child re-renders anyway<br>  const handleAction = () =&gt; {<br>    console.log(&#39;Current count:&#39;, count);<br>  };</pre><pre>  // ✅ handleAction reference stays stable when theme changes<br>  // React.memo works correctly — child skips unnecessary renders<br>  const handleActionStable = useCallback(() =&gt; {<br>    console.log(&#39;Current count:&#39;, count);<br>  }, [count]); // Only recreated when count changes</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setTheme(t =&gt; t === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount(c =&gt; c + 1)}&gt;<br>        Increment Count<br>      &lt;/button&gt;<br>      &lt;ChildComponent onAction={handleActionStable} label=&quot;Trigger&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The critical point: <strong>without </strong><strong>React.memo, </strong><strong>useCallback is meaningless</strong>. They only work together. Using one without the other is equivalent to using neither.</p><h3>Situation 2: A function lives inside a useEffect dependency array</h3><p>React determines when to re-run a useEffect by comparing the previous and current values of everything in its dependency array. If a function is recreated every render, it always has a new reference, which means the effect fires every render.</p><pre>// ❌ Infinite loop risk<br>function SearchComponent({ query }) {<br>  // fetchResults gets a new reference every render<br>  const fetchResults = async () =&gt; {<br>    const response = await fetch(`/api/search?q=${query}`);<br>    return response.json();<br>  };</pre><pre>  useEffect(() =&gt; {<br>    fetchResults();<br>  }, [fetchResults]); // New reference every render → effect fires every render → re-render → repeat<br>}</pre><pre>// ✅ Controlled execution<br>function SearchComponent({ query }) {<br>  const fetchResults = useCallback(async () =&gt; {<br>    const response = await fetch(`/api/search?q=${query}`);<br>    return response.json();<br>  }, [query]); // Only recreated when query changes</pre><pre>  useEffect(() =&gt; {<br>    fetchResults();<br>  }, [fetchResults]); // Stable reference → effect fires only when query changes<br>}</pre><p>Here useCallback isn&#39;t a performance optimization — it&#39;s a <strong>correctness guarantee</strong>. Without it, the code is broken.</p><h3>When not to use it</h3><pre>// ❌ Function is only used within the same component<br>const handleSubmit = useCallback(() =&gt; {<br>  validateAndSubmit(formData);<br>}, [formData]);</pre><pre>// ❌ Event handler with no React.memo child receiving it<br>const handleMenuOpen = useCallback(() =&gt; {<br>  setMenuOpen(true);<br>}, []);</pre><pre>// ❌ Simple, pure utility function<br>const getLabel = useCallback((id) =&gt; {<br>  return labels[id] ?? &#39;Unknown&#39;;<br>}, [labels]);</pre><pre>// ❌ Inline — already creates a new function on every render anyway<br>&lt;button onClick={useCallback(() =&gt; doSomething(), [])}&gt;Click&lt;/button&gt;</pre><p>In all of these cases, adding useCallback reduces readability and wastes memory. The app is strictly worse for it.</p><h3>useMemo: Two distinct problems, one hook — most articles only cover one</h3><p>useMemo is typically defined as &quot;for expensive computations.&quot; That&#39;s true but incomplete. It&#39;s also used for referential stability — and that use case comes up far more often in practice.</p><h3>Problem 1: Genuinely expensive computations</h3><pre>function ReportDashboard({ transactions, dateRange, filters }) {<br>  // Iterating over thousands of records with multiple filter conditions<br>  const summary = useMemo(() =&gt; {<br>    const filtered = transactions.filter(t =&gt; {<br>      return (<br>        t.date &gt;= dateRange.start &amp;&amp;<br>        t.date &lt;= dateRange.end &amp;&amp;<br>        filters.categories.includes(t.category) &amp;&amp;<br>        t.amount &gt;= filters.minAmount<br>      );<br>    });</pre><pre>    return {<br>      total: filtered.reduce((sum, t) =&gt; sum + t.amount, 0),<br>      count: filtered.length,<br>      byCategory: filtered.reduce((acc, t) =&gt; {<br>        acc[t.category] = (acc[t.category] ?? 0) + t.amount;<br>        return acc;<br>      }, {}),<br>      average: filtered.length &gt; 0<br>        ? filtered.reduce((sum, t) =&gt; sum + t.amount, 0) / filtered.length<br>        : 0,<br>    };<br>  }, [transactions, dateRange, filters]);</pre><pre>  return &lt;SummaryCard data={summary} /&gt;;<br>}</pre><p>But there’s an important question here: is this actually expensive?</p><p>If transactions typically contains 50 to 100 items — probably not. Adding useMemo in that scenario provides no measurable benefit.</p><p><strong>The rule:</strong> don’t call something expensive before you’ve measured it. Chrome DevTools Performance tab or React DevTools Profiler will give you real numbers. Measure first, optimize second.</p><h3>Problem 2: Referential stability (the more commonly needed use case)</h3><p>This is less discussed but solves a problem that comes up constantly in real applications.</p><pre>function UserDashboard({ userId, role }) {<br>  // ❌ This object is recreated every render<br>  // useEffect sees a new reference every time — fires on every render<br>  const requestConfig = {<br>    endpoint: `/api/users/${userId}/dashboard`,<br>    headers: {<br>      &#39;X-User-Id&#39;: userId,<br>      &#39;X-User-Role&#39;: role,<br>    },<br>    retryCount: 3,<br>  };</pre><pre>  useEffect(() =&gt; {<br>    initializeDashboard(requestConfig);<br>  }, [requestConfig]); // New reference every render → runs every render<br>}</pre><pre>function UserDashboard({ userId, role }) {<br>  // ✅ Same reference as long as userId and role don&#39;t change<br>  const requestConfig = useMemo(() =&gt; ({<br>    endpoint: `/api/users/${userId}/dashboard`,<br>    headers: {<br>      &#39;X-User-Id&#39;: userId,<br>      &#39;X-User-Role&#39;: role,<br>    },<br>    retryCount: 3,<br>  }), [userId, role]);</pre><pre>  useEffect(() =&gt; {<br>    initializeDashboard(requestConfig);<br>  }, [requestConfig]); // Fires only when userId or role changes<br>}</pre><p>The same applies to arrays:</p><pre>function FilteredList({ categoryId }) {<br>  // ❌ New array reference on every render<br>  const defaultFilters = [&#39;active&#39;, &#39;verified&#39;];</pre><pre>  // ✅ Stable reference — only created once<br>  const defaultFilters = useMemo(() =&gt; [&#39;active&#39;, &#39;verified&#39;], []);</pre><pre>  useEffect(() =&gt; {<br>    applyFilters(defaultFilters);<br>  }, [defaultFilters]);<br>}</pre><h3>Decision table</h3><p>Situation Reach for Function → prop of a React.memo child useCallback Function → inside a useEffect dependency array useCallback Profiler-verified expensive computation useMemo Object/array → inside a useEffect dependency array useMemo Object/array → prop of a React.memo child useMemo Function used only within the same component ❌ Neither Simple computation, small data set ❌ Neither &quot;Probably expensive&quot; computation (not measured) ❌ Profile first</p><h3>Common mistakes worth naming</h3><h3>Mistake 1: useCallback without React.memo</h3><pre>// ❌ No React.memo — useCallback does nothing useful here<br>function Parent() {<br>  const handleChange = useCallback((value) =&gt; {<br>    updateValue(value);<br>  }, []);</pre><pre>  return &lt;Input onChange={handleChange} /&gt;; // Input is not wrapped in React.memo<br>}</pre><pre>// ✅ React.memo is present — now useCallback is meaningful<br>const Input = React.memo(({ onChange, placeholder }) =&gt; {<br>  return &lt;input onChange={onChange} placeholder={placeholder} /&gt;;<br>});</pre><pre>function Parent() {<br>  const handleChange = useCallback((value) =&gt; {<br>    updateValue(value);<br>  }, []);</pre><pre>  return &lt;Input onChange={handleChange} placeholder=&quot;Search...&quot; /&gt;;<br>}</pre><h3>Mistake 2: Missing values in the dependency array</h3><pre>// ❌ userId is used but missing from deps — stale closure<br>const fetchUser = useCallback(async () =&gt; {<br>  const data = await api.get(`/users/${userId}`);<br>  setUser(data);<br>}, []); // userId changes won&#39;t be reflected — old value is captured</pre><pre>// ✅ All external values included in deps<br>const fetchUser = useCallback(async () =&gt; {<br>  const data = await api.get(`/users/${userId}`);<br>  setUser(data);<br>}, [userId]);</pre><p>This is a particularly painful bug because it’s invisible. The function runs, returns data, no errors — just the wrong data.</p><h3>Mistake 3: Memoizing everything out of habit</h3><pre>// ❌ None of this needs memoization<br>function SimpleCard({ title, description, count }) {<br>  const formattedCount = useMemo(() =&gt; count.toLocaleString(&#39;en-US&#39;), [count]);<br>  const titleUpperCase = useMemo(() =&gt; title.toUpperCase(), [title]);<br>  const handleClick = useCallback(() =&gt; setExpanded(e =&gt; !e), []);</pre><pre>  return (<br>    &lt;div onClick={handleClick}&gt;<br>      &lt;h2&gt;{titleUpperCase}&lt;/h2&gt;<br>      &lt;p&gt;{description}&lt;/p&gt;<br>      &lt;span&gt;{formattedCount}&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// ✅ Clean, readable, and just as fast in practice<br>function SimpleCard({ title, description, count }) {<br>  return (<br>    &lt;div onClick={() =&gt; setExpanded(e =&gt; !e)}&gt;<br>      &lt;h2&gt;{title.toUpperCase()}&lt;/h2&gt;<br>      &lt;p&gt;{description}&lt;/p&gt;<br>      &lt;span&gt;{count.toLocaleString(&#39;en-US&#39;)}&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The memoized version has more cognitive overhead, more lines, and performs identically or worse.</p><h3>React Compiler and where this is all going</h3><p>React 19 ships with <strong>React Compiler</strong> (previously called React Forget), which will automatically handle most of these memoization decisions. It analyzes your code at build time and inserts memoization where it’s actually needed.</p><p>What this means for you today:</p><p>If you’re in the habit of wrapping everything in useCallback and useMemo defensively, you&#39;re building instincts that won&#39;t transfer well. When the Compiler becomes standard, unnecessary wrappers become noise — they interfere with readability and can conflict with the Compiler&#39;s own decisions.</p><p>The right instinct to build now: <strong>write simple code first. Optimize what the profiler shows you. Don’t memoize problems you don’t have.</strong></p><h3>Takeaway</h3><p>useCallback and useMemo are legitimate tools — but only when applied to the right problem.</p><ul><li>useCallback: use it when you&#39;re passing a function to a React.memo child, or when a function is in a useEffect dependency array.</li><li>useMemo: use it when a computation is provably expensive, or when an object or array needs referential stability for useEffect or React.memo.</li><li>Neither: when none of the above applies, write the simple version.</li></ul><p>Next time you see useCallback or useMemo in a code review, ask one question: <em>&quot;What specific problem is this solving?&quot;</em></p><p>If the answer isn’t clear — it probably shouldn’t be there.</p><p><em>I write about real-world React and Spring Boot patterns — things that actually come up in production. Follow along if that’s useful.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6a5e6ee797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useCallback ve useMemo: Çoğu Kaynak Sana Yarısını Anlatıyor]]></title>
            <link>https://medium.com/@sahin.ilyd/usecallback-ve-usememo-%C3%A7o%C4%9Fu-kaynak-sana-yar%C4%B1s%C4%B1n%C4%B1-anlat%C4%B1yor-5d9a292299fd?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9a292299fd</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 13:42:57 GMT</pubDate>
            <atom:updated>2026-04-02T13:42:57.796Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Optimizasyon yapmak ile optimizasyon yapar gibi görünmek arasındaki fark.</em></p><p>Production code review’larında en çok şu ikisini görüyorum: ya hiç kullanılmamış, ya her yere eklenmiş.</p><pre>const handleClick = useCallback(() =&gt; {<br>  setCount(c =&gt; c + 1);<br>}, []);</pre><p>Bu kod çalışıyor. Test geçiyor. Ama bu useCallback gereksiz — üstelik uygulamayı hafifçe yavaşlatıyor.</p><p>Sebep şu: “useCallback performans için kullanılır” açıklaması her yerde böyle yazıyor. Bu tanım eksik. Eksik olduğu için de yanlış yerlerde kullanılıyor.</p><p>useCallback ile useMemo&#39;yu gerçekten ne zaman kullanmanız gerektiğini, ne zaman kullanmamanız gerektiğini ve ikisi arasındaki kritik farkı somut örneklerle açıklıyorum.</p><h3>Temel yanılgı: “Performans hook’u” diye bir şey yok</h3><p>React dokümantasyonu artık bunu açıkça yazıyor ama çoğu kaynak hâlâ eski anlatımı tekrar ediyor.</p><p>useCallback ve useMemo belleği <strong>tüketir</strong>. Her render&#39;da dependency karşılaştırması yapılır. Bu karşılaştırmanın da bir maliyeti vardır. Yani bu hook&#39;ları kullanmak &quot;ücretsiz optimizasyon&quot; değil — bilinçli bir <strong>trade-off</strong>.</p><p>Yanlış yerde kullanırsanız, optimize ettiğinizi sandığınız kod aslında daha fazla iş yapıyor olur. Component küçükse, render sayısı azsa, hesaplama basitse — bu hook’ları eklemeniz net bir <strong>yavaşlamaya</strong> neden olabilir.</p><p>Peki ne zaman kullanmalısınız?</p><h3>useCallback: Sadece iki durumda anlamlı</h3><p>useCallback, bir fonksiyonu memoize eder. Dependency&#39;ler değişmediği sürece aynı fonksiyon referansını döndürür.</p><p>Referans kararlılığının önemli olduğu iki durum vardır.</p><h3>Durum 1: React.memo ile sarılmış bir child component’e prop olarak geçiyorsa</h3><p>React.memo, bir component&#39;i yalnızca props&#39;ları değiştiğinde yeniden render eder. Ama JavaScript&#39;te iki fonksiyon hiçbir zaman referans olarak eşit değildir — her seferinde yeniden oluşturulursa.</p><pre>const fn1 = () =&gt; {};<br>const fn2 = () =&gt; {};<br>console.log(fn1 === fn2); // false — her seferinde yeni referans</pre><p>Bu yüzden React.memo kullanıyorsanız ve child&#39;a fonksiyon prop geçiyorsanız, o fonksiyonun referansı stabil olmalı. Aksi hâlde React.memo&#39;nun hiçbir etkisi kalmaz.</p><pre>// ChildComponent yalnızca onAction değişince re-render olsun istiyoruz<br>const ChildComponent = React.memo(({ onAction, label }) =&gt; {<br>  console.log(&#39;ChildComponent render edildi&#39;);<br>  return &lt;button onClick={onAction}&gt;{label}&lt;/button&gt;;<br>});</pre><pre>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br>  const [theme, setTheme] = useState(&#39;light&#39;);</pre><pre>  // ❌ theme değiştiğinde handleAction yeniden oluşur<br>  // React.memo bunu fark edemez — child yeniden render edilir<br>  const handleAction = () =&gt; {<br>    console.log(&#39;Mevcut count:&#39;, count);<br>  };</pre><pre>  // ✅ theme değişse de handleAction referansı sabit kalır<br>  // React.memo çalışır — child gereksiz yere render edilmez<br>  const handleActionStable = useCallback(() =&gt; {<br>    console.log(&#39;Mevcut count:&#39;, count);<br>  }, [count]); // Yalnızca count değişince yeniden oluşur</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setTheme(t =&gt; t === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)}&gt;<br>        Temayı Değiştir<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount(c =&gt; c + 1)}&gt;<br>        Sayacı Artır<br>      &lt;/button&gt;<br>      {/* useCallback olmadan: tema değişince child da render edilir */}<br>      &lt;ChildComponent onAction={handleActionStable} label=&quot;Tetikle&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Kritik nokta şu: <strong>React.memo yoksa </strong><strong>useCallback&#39;in de anlamı yok.</strong> İkisi birbirini tamamlar. Birini kullanıp diğerini unutmak, hiç kullanmamakla eşdeğerdir.</p><h3>Durum 2: useEffect’in dependency array’inde fonksiyon kullanılıyorsa</h3><p>React, useEffect&#39;in ne zaman tetikleneceğini dependency array&#39;indeki değerlerin referansına bakarak belirler. Eğer bir fonksiyon her render&#39;da yeniden oluşuyorsa, useEffect her render&#39;da tetiklenir.</p><pre>// ❌ Sonsuz döngü riski<br>function SearchComponent({ query }) {<br>  // fetchResults her render&#39;da yeniden oluşur<br>  const fetchResults = async () =&gt; {<br>    const response = await fetch(`/api/search?q=${query}`);<br>    return response.json();<br>  };</pre><pre>  useEffect(() =&gt; {<br>    fetchResults();<br>  }, [fetchResults]); // fetchResults her seferinde yeni referans → sonsuz döngü<br>}</pre><pre>// ✅ Kontrollü tetiklenme<br>function SearchComponent({ query }) {<br>  const fetchResults = useCallback(async () =&gt; {<br>    const response = await fetch(`/api/search?q=${query}`);<br>    return response.json();<br>  }, [query]); // Yalnızca query değişince yeniden oluşur</pre><pre>  useEffect(() =&gt; {<br>    fetchResults();<br>  }, [fetchResults]); // fetchResults stabil → effect yalnızca query değişince çalışır<br>}</pre><p>Burada useCallback bir &quot;performans optimizasyonu&quot; değil, <strong>doğruluk garantisi</strong>. Olmazsa kod hatalı çalışır.</p><h3>Kullanmamanız gereken durumlar</h3><pre>// ❌ Fonksiyon sadece aynı component içinde kullanılıyorsa<br>const handleSubmit = useCallback(() =&gt; {<br>  validateAndSubmit(formData);<br>}, [formData]);</pre><pre>// ❌ Event handler ve React.memo&#39;lu child yoksa<br>const handleMenuOpen = useCallback(() =&gt; {<br>  setMenuOpen(true);<br>}, []);</pre><pre>// ❌ Basit, saf bir hesaplama yapılıyorsa<br>const getLabel = useCallback((id) =&gt; {<br>  return labels[id] ?? &#39;Bilinmiyor&#39;;<br>}, [labels]);</pre><pre>// ❌ Inline event handler — zaten her seferinde yeni fonksiyon<br>&lt;button onClick={useCallback(() =&gt; doSomething(), [])}&gt;Tıkla&lt;/button&gt;</pre><p>Bu örneklerin hepsinde useCallback eklemek yalnızca okunabilirliği düşürür ve gereksiz bellek kullanır.</p><h3>useMemo: İki farklı problemi çözüyor, çoğu kaynak sadece birini anlatıyor</h3><p>useMemo genellikle &quot;pahalı hesaplamalar için&quot; diye tanımlanır. Bu doğru ama eksik. Referans kararlılığı için de kullanılır — ve bu kullanım çok daha yaygın ihtiyaç doğurur.</p><h3>Problem 1: Gerçekten pahalı hesaplamalar</h3><pre>function ReportDashboard({ transactions, dateRange, filters }) {<br>  // Her render&#39;da binlerce transaction üzerinde işlem yapılıyor<br>  const summary = useMemo(() =&gt; {<br>    const filtered = transactions.filter(t =&gt; {<br>      return (<br>        t.date &gt;= dateRange.start &amp;&amp;<br>        t.date &lt;= dateRange.end &amp;&amp;<br>        filters.categories.includes(t.category) &amp;&amp;<br>        t.amount &gt;= filters.minAmount<br>      );<br>    });</pre><pre>    return {<br>      total: filtered.reduce((sum, t) =&gt; sum + t.amount, 0),<br>      count: filtered.length,<br>      byCategory: filtered.reduce((acc, t) =&gt; {<br>        acc[t.category] = (acc[t.category] ?? 0) + t.amount;<br>        return acc;<br>      }, {}),<br>      average: filtered.length &gt; 0<br>        ? filtered.reduce((sum, t) =&gt; sum + t.amount, 0) / filtered.length<br>        : 0,<br>    };<br>  }, [transactions, dateRange, filters]);</pre><pre>  return &lt;SummaryCard data={summary} /&gt;;<br>}</pre><p>Ama burada önemli bir soru: bu hesaplama gerçekten pahalı mı?</p><p>Eğer transactions dizisi genellikle 50-100 eleman içeriyorsa — muhtemelen değil. useMemo eklemek bu durumda net bir kazanç sağlamaz.</p><p><strong>Kural:</strong> Profiler açmadan “bu pahalı” demeyin. Chrome DevTools’un Performance sekmesi veya React DevTools Profiler size kesin cevap verir. Önce ölçün, sonra optimize edin.</p><h3>Problem 2: Referans kararlılığı (çok daha sık ihtiyaç duyulan durum)</h3><p>Bu kullanım daha az bilinir ama pratikte çok daha sık karşılaşılan bir sorunu çözer.</p><pre>function UserDashboard({ userId, role }) {<br>  // ❌ Bu obje her render&#39;da yeniden oluşur<br>  // useEffect her seferinde tetiklenir — istek patlaması yaşanır<br>  const requestConfig = {<br>    endpoint: `/api/users/${userId}/dashboard`,<br>    headers: {<br>      &#39;X-User-Id&#39;: userId,<br>      &#39;X-User-Role&#39;: role,<br>    },<br>    retryCount: 3,<br>  };</pre><pre>  useEffect(() =&gt; {<br>    initializeDashboard(requestConfig);<br>  }, [requestConfig]); // Her render&#39;da yeni referans → sonsuz döngü<br>}</pre><pre>function UserDashboard({ userId, role }) {<br>  // ✅ userId veya role değişmediği sürece aynı referans<br>  const requestConfig = useMemo(() =&gt; ({<br>    endpoint: `/api/users/${userId}/dashboard`,<br>    headers: {<br>      &#39;X-User-Id&#39;: userId,<br>      &#39;X-User-Role&#39;: role,<br>    },<br>    retryCount: 3,<br>  }), [userId, role]);</pre><pre>  useEffect(() =&gt; {<br>    initializeDashboard(requestConfig);<br>  }, [requestConfig]); // Artık yalnızca userId veya role değişince tetiklenir<br>}</pre><p>Aynı durum array’ler için de geçerlidir:</p><pre>function FilteredList({ categoryId }) {<br>  // ❌ Her render&#39;da yeni dizi referansı<br>  const defaultFilters = [&#39;active&#39;, &#39;verified&#39;];</pre><pre>  // ✅ Stabil referans<br>  const defaultFilters = useMemo(() =&gt; [&#39;active&#39;, &#39;verified&#39;], []);</pre><pre>  useEffect(() =&gt; {<br>    applyFilters(defaultFilters);<br>  }, [defaultFilters]);<br>}</pre><h3>Karar tablosu</h3><p>Durum Kullanım Fonksiyon → React.memo&#39;lu child&#39;a prop useCallback Fonksiyon → useEffect dependency&#39;si useCallback Profiler&#39;da kanıtlanmış pahalı hesaplama useMemo Obje/array → useEffect dependency&#39;si useMemo Obje/array → React.memo&#39;lu child&#39;a prop useMemo Yalnızca aynı component içinde kullanılan fonksiyon ❌ Hiçbiri Basit hesaplama, küçük veri seti ❌ Hiçbiri Ölçülmemiş &quot;pahalı olabilir&quot; hesaplama ❌ Önce profiler</p><h3>Sık yapılan hatalar</h3><h3>Hata 1: React.memo olmadan useCallback kullanmak</h3><pre>// ❌ React.memo yok — useCallback anlamsız<br>function Parent() {<br>  const handleChange = useCallback((value) =&gt; {<br>    updateValue(value);<br>  }, []);</pre><pre>  return &lt;Input onChange={handleChange} /&gt;; // Input React.memo ile sarılı değil<br>}</pre><pre>// ✅ React.memo varsa anlamlı<br>const Input = React.memo(({ onChange, placeholder }) =&gt; {<br>  return &lt;input onChange={onChange} placeholder={placeholder} /&gt;;<br>});</pre><pre>function Parent() {<br>  const handleChange = useCallback((value) =&gt; {<br>    updateValue(value);<br>  }, []);</pre><pre>  return &lt;Input onChange={handleChange} placeholder=&quot;Ara...&quot; /&gt;;<br>}</pre><h3>Hata 2: Dependency array’i yanlış yazmak</h3><pre>// ❌ userId dependency&#39;de yok ama kullanılıyor — stale closure<br>const fetchUser = useCallback(async () =&gt; {<br>  const data = await api.get(`/users/${userId}`);<br>  setUser(data);<br>}, []); // userId değişse de fonksiyon eski userId&#39;yi kullanır</pre><pre>// ✅ Tüm dış değerler dependency&#39;de<br>const fetchUser = useCallback(async () =&gt; {<br>  const data = await api.get(`/users/${userId}`);<br>  setUser(data);<br>}, [userId]);</pre><h3>Hata 3: Her şeyi memoize etmeye çalışmak</h3><pre>// ❌ Bunların hiçbirinin memoize edilmesine gerek yok<br>function SimpleCard({ title, description, count }) {<br>  const formattedCount = useMemo(() =&gt; count.toLocaleString(&#39;tr-TR&#39;), [count]);<br>  const titleUpperCase = useMemo(() =&gt; title.toUpperCase(), [title]);<br>  const handleClick = useCallback(() =&gt; setExpanded(e =&gt; !e), []);</pre><pre>  return (<br>    &lt;div onClick={handleClick}&gt;<br>      &lt;h2&gt;{titleUpperCase}&lt;/h2&gt;<br>      &lt;p&gt;{description}&lt;/p&gt;<br>      &lt;span&gt;{formattedCount}&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// ✅ Sade, okunabilir, yeterli performanslı<br>function SimpleCard({ title, description, count }) {<br>  return (<br>    &lt;div onClick={() =&gt; setExpanded(e =&gt; !e)}&gt;<br>      &lt;h2&gt;{title.toUpperCase()}&lt;/h2&gt;<br>      &lt;p&gt;{description}&lt;/p&gt;<br>      &lt;span&gt;{count.toLocaleString(&#39;tr-TR&#39;)}&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>React Compiler ve gelecek</h3><p>React 19 ile birlikte gelen <strong>React Compiler</strong> (eski adıyla React Forget), bu memoization kararlarının büyük bir kısmını otomatik olarak yönetecek. Build aşamasında kodu analiz edip gerekli yerlere otomatik memoization ekleyecek.</p><p>Bu ne anlama geliyor?</p><p>Eğer bugün useCallback ve useMemo&#39;yu &quot;her yere ekleyeyim, zararı olmaz&quot; mantığıyla kullanıyorsanız, yanlış bir alışkanlık ediniyorsunuz. Compiler geldiğinde gereksiz sarmallar hem okunabilirliği bozar hem de Compiler&#39;ın optimizasyon kararlarıyla çakışabilir.</p><p>Bugün için doğru yaklaşım şu: <strong>Önce sade yaz. Profiler’da gördüğünü optimize et. Gerçek bir problem olmadan memoize etme.</strong></p><h3>Özet</h3><p>useCallback ve useMemo güçlü araçlar — ama yalnızca doğru yerde kullanıldığında.</p><ul><li>useCallback: React.memo&#39;lu child&#39;a fonksiyon geçiyorsanız veya fonksiyon useEffect&#39;in dependency&#39;sindeyse kullanın.</li><li>useMemo: Gerçekten pahalı bir hesaplama varsa (profiler&#39;la kanıtlanmış) veya bir obje/array useEffect ya da React.memo child&#39;ına geçiyorsa kullanın.</li><li>İkisi de yoksa: sade kod yazın.</li></ul><p>Bir sonraki code review’da useCallback veya useMemo gördüğünüzde kendinize tek bir soru sorun: <em>&quot;Bu neden burada? Hangi somut problemi çözüyor?&quot;</em></p><p>Cevap net değilse — büyük ihtimalle orada olmamalı.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9a292299fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Design Reference]]></title>
            <link>https://medium.com/@sahin.ilyd/rest-api-design-reference-5b9b432ca165?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b9b432ca165</guid>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 10:57:49 GMT</pubDate>
            <atom:updated>2026-04-01T10:57:49.246Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>This guide goes beyond basic CRUD. It covers HTTP semantics, idempotency, optimistic locking, N+1 problems, cache strategies, distributed tracing, and observability — through the lens of Spring Boot and React.</em></blockquote><h3>Table of Contents</h3><ol><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#1-http-semantics-and-idempotency">HTTP Semantics and Idempotency</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#2-url-design-and-resource-modeling">URL Design and Resource Modeling</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#3-http-status-codes--nuances-and-traps">HTTP Status Codes — Nuances and Traps</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#4-standardized-error-structure-and-problem-details-rfc-7807">Standardized Error Structure and Problem Details (RFC 7807)</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#5-request-validation--a-layered-strategy">Request Validation — A Layered Strategy</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#6-pagination-cursor-based-paging-and-filtering">Pagination, Cursor-Based Paging, and Filtering</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#7-dto-design-projections-and-cqrs-separation">DTO Design, Projections, and CQRS Separation</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#8-optimistic-locking-and-concurrency-control">Optimistic Locking and Concurrency Control</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#9-idempotency-keys--making-post-safe">Idempotency Keys — Making POST Safe</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#10-conditional-requests--etag-and-if-modified-since">Conditional Requests — ETag and If-Modified-Since</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#11-api-versioning--strategy-and-deprecation">API Versioning — Strategy and Deprecation</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#12-authentication-authorization-and-fine-grained-access">Authentication, Authorization, and Fine-Grained Access</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#13-cors-and-security-headers">CORS and Security Headers</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#14-rate-limiting-and-throttling-strategies">Rate Limiting and Throttling Strategies</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#15-the-n1-problem-and-database-optimization">The N+1 Problem and Database Optimization</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#16-observability--logging-metrics-and-distributed-tracing">Observability — Logging, Metrics, and Distributed Tracing</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#17-openapi-and-contract-first-development">OpenAPI and Contract-First Development</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#18-advanced-api-layer-on-the-react-side">Advanced API Layer on the React Side</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#19-production-readiness-checklist">Production Readiness Checklist</a></li></ol><h3>1. HTTP Semantics and Idempotency</h3><p>HTTP methods are a contract. Violating that contract causes proxies, CDNs, load balancers, and clients to behave in unexpected ways — sometimes silently.</p><h3>Why Idempotency Matters in Production</h3><p>When a request fails due to a network interruption, should the client retry? The answer depends entirely on whether the method is idempotent.</p><pre>GET    /orders/123  → Always safe to retry (safe + idempotent)<br>PUT    /orders/123  → Safe to retry (idempotent)<br>DELETE /orders/123  → Safe to retry (idempotent)<br>POST   /orders      → DANGEROUS — could create a duplicate order (not idempotent)<br>PATCH  /orders/123  → Depends on the payload — must be analyzed carefully</pre><h3>The PATCH Idempotency Trap</h3><pre>// Two very different types of PATCH payloads</pre><pre>// 1. Absolute value patch — idempotent, safe to retry<br>{ &quot;status&quot;: &quot;CANCELLED&quot; }</pre><pre>// 2. Relative / delta patch — NOT idempotent, dangerous<br>{ &quot;quantity&quot;: { &quot;increment&quot;: 1 } }</pre><p>A relative increment is not idempotent. Sending the same request twice increments the quantity twice. For operations like this, the idempotency key mechanism covered in <a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#9-idempotency-keys--making-post-safe">Section 9</a> must be applied.</p><h3>Full CRUD Controller</h3><pre>@RestController<br>@RequestMapping(&quot;/api/v1/orders&quot;)<br>@RequiredArgsConstructor<br>@Validated<br>public class OrderController {</pre><pre>    private final OrderService orderService;</pre><pre>    @GetMapping<br>    public ResponseEntity&lt;PagedModel&lt;OrderDTO&gt;&gt; list(<br>        @Valid OrderFilter filter,<br>        @PageableDefault(size = 20, sort = &quot;createdAt&quot;, direction = DESC) Pageable pageable<br>    ) {<br>        return ResponseEntity.ok(orderService.findAll(filter, pageable));<br>    }</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; get(@PathVariable UUID id) {<br>        return ResponseEntity.ok(orderService.findById(id));<br>    }</pre><pre>    @PostMapping<br>    public ResponseEntity&lt;OrderDTO&gt; create(<br>        @Valid @RequestBody CreateOrderRequest request,<br>        @RequestHeader(value = &quot;Idempotency-Key&quot;, required = false) String idempotencyKey<br>    ) {<br>        OrderDTO order = orderService.create(request, idempotencyKey);<br>        return ResponseEntity<br>            .created(URI.create(&quot;/api/v1/orders/&quot; + order.id()))<br>            .body(order);<br>    }</pre><pre>    @PutMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; replace(<br>        @PathVariable UUID id,<br>        @Valid @RequestBody ReplaceOrderRequest request<br>    ) {<br>        return ResponseEntity.ok(orderService.replace(id, request));<br>    }</pre><pre>    @PatchMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; patch(<br>        @PathVariable UUID id,<br>        @Valid @RequestBody PatchOrderRequest request<br>    ) {<br>        return ResponseEntity.ok(orderService.patch(id, request));<br>    }</pre><pre>    @DeleteMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Void&gt; delete(@PathVariable UUID id) {<br>        orderService.delete(id);<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><h3>2. URL Design and Resource Modeling</h3><p>URL design is an architectural decision. A poor design leads to costly breaking changes in future versions.</p><h3>Hierarchy — When Flat, When Nested?</h3><pre># Deeply nested — avoid this<br>/users/{userId}/departments/{deptId}/teams/{teamId}/members/{memberId}/tasks/{taskId}</pre><pre># Flat + relationship parameters — prefer this<br>/tasks?memberId={memberId}&amp;teamId={teamId}</pre><pre># Sensible nesting (2 levels is fine)<br>/orders/{orderId}/items<br>/users/{userId}/addresses</pre><p><strong>Rule:</strong> A sub-resource can be nested if it has no independent identity outside its parent. If it can stand alone, keep it flat.</p><h3>Action Endpoints — RPC Traps</h3><pre># Wrong — ignores HTTP method semantics<br>POST /orders/cancel         → which order?<br>GET  /orders/sendEmail      → GET with side effects</pre><pre># Better — model as sub-resource<br>POST /orders/{id}/cancellation<br>POST /orders/{id}/notifications</pre><pre># Best — state machine approach<br>PATCH /orders/{id}<br>Body: { &quot;status&quot;: &quot;CANCELLED&quot; }</pre><h3>Query Parameter Standards</h3><pre># Filtering<br>GET /products?category=electronics&amp;minPrice=100&amp;maxPrice=500</pre><pre># Sorting — single parameter, multiple fields<br>GET /products?sort=price:asc,name:desc</pre><pre># Sparse fieldsets<br>GET /users?fields=id,name,email</pre><pre># Embedding related resources<br>GET /orders?include=items,customer</pre><h3>3. HTTP Status Codes — Nuances and Traps</h3><h3>The Most Commonly Misused Codes</h3><p><strong>200 vs 201:</strong></p><pre>// Wrong — returning 200 after creating a resource<br>@PostMapping<br>public ResponseEntity&lt;UserDTO&gt; create(...) {<br>    return ResponseEntity.ok(userService.create(request)); // 200 ❌<br>}</pre><pre>// Correct — 201 + Location header<br>@PostMapping<br>public ResponseEntity&lt;UserDTO&gt; create(...) {<br>    UserDTO user = userService.create(request);<br>    return ResponseEntity<br>        .created(URI.create(&quot;/api/v1/users/&quot; + user.id()))<br>        .body(user); // 201 ✅<br>}</pre><p><strong>401 vs 403:</strong></p><pre>401 Unauthorized → &quot;I don&#39;t know who you are — please authenticate&quot;<br>403 Forbidden    → &quot;I know who you are but you don&#39;t have access&quot;</pre><pre>Token missing       → 401<br>Token expired       → 401<br>Token valid but no permission → 403</pre><p><strong>404 vs 403 — Information Leakage:</strong></p><pre>// Security trap — returning 403 reveals the resource exists<br>if (!order.belongsTo(currentUser)) {<br>    throw new ForbiddenException(); // 403 → leaks resource existence<br>}</pre><pre>// More secure — silently deny existence<br>if (!order.belongsTo(currentUser)) {<br>    throw new ResourceNotFoundException(); // 404 → silent rejection<br>}</pre><p><strong>422 vs 400:</strong></p><pre>400 Bad Request          → Structural / parse error (malformed JSON)<br>422 Unprocessable Entity → Parsed successfully but field or business rule validation failed</pre><h3>4. Standardized Error Structure and Problem Details (RFC 7807)</h3><p>Rather than inventing your own error format, use the industry-standard RFC 7807 Problem Details. This format is recognized by Swagger, API gateways, and monitoring tools.</p><h3>Problem Details Model</h3><pre>public record ProblemDetail(<br>    String type,       // URI pointing to error type documentation<br>    String title,      // Short, human-readable summary<br>    int status,        // HTTP status code<br>    String detail,     // Request-specific description<br>    String instance,   // URI identifying this specific occurrence<br>    Instant timestamp,<br>    Map&lt;String, Object&gt; extensions<br>) {}</pre><h3>Global Exception Handler — Full Implementation</h3><pre>@RestControllerAdvice<br>@Slf4j<br>public class GlobalExceptionHandler {</pre><pre>    private static final String BASE_TYPE = &quot;https://api.yourdomain.com/errors/&quot;;</pre><pre>    @ExceptionHandler(ResourceNotFoundException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleNotFound(<br>        ResourceNotFoundException ex, HttpServletRequest req<br>    ) {<br>        return problem(HttpStatus.NOT_FOUND, &quot;not-found&quot;, ex.getMessage(), req);<br>    }</pre><pre>    @ExceptionHandler(BusinessRuleViolationException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleBusinessRule(<br>        BusinessRuleViolationException ex, HttpServletRequest req<br>    ) {<br>        return problem(HttpStatus.UNPROCESSABLE_ENTITY,<br>            &quot;business-rule-violation&quot;, ex.getMessage(), req);<br>    }</pre><pre>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleValidation(<br>        MethodArgumentNotValidException ex, HttpServletRequest req<br>    ) {<br>        List&lt;FieldError&gt; violations = ex.getBindingResult()<br>            .getFieldErrors()<br>            .stream()<br>            .map(e -&gt; new FieldError(e.getField(), e.getDefaultMessage(), e.getRejectedValue()))<br>            .toList();</pre><pre>        ProblemDetail body = new ProblemDetail(<br>            BASE_TYPE + &quot;validation-error&quot;, &quot;Validation Failed&quot;,<br>            422, &quot;One or more fields failed validation&quot;,<br>            req.getRequestURI(), Instant.now(),<br>            Map.of(&quot;violations&quot;, violations)<br>        );</pre><pre>        return ResponseEntity.unprocessableEntity()<br>            .contentType(MediaType.APPLICATION_PROBLEM_JSON)<br>            .body(body);<br>    }</pre><pre>    @ExceptionHandler(OptimisticLockingFailureException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleOptimisticLock(<br>        OptimisticLockingFailureException ex, HttpServletRequest req<br>    ) {<br>        return problem(HttpStatus.CONFLICT, &quot;optimistic-lock-conflict&quot;,<br>            &quot;The resource was modified by another request. Fetch the latest version and retry.&quot;, req);<br>    }</pre><pre>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleGeneral(<br>        Exception ex, HttpServletRequest req<br>    ) {<br>        log.error(&quot;Unhandled exception on {} {}&quot;, req.getMethod(), req.getRequestURI(), ex);<br>        // Never leak stack traces to the client<br>        return problem(HttpStatus.INTERNAL_SERVER_ERROR, &quot;internal-error&quot;,<br>            &quot;An unexpected error occurred. Please contact support.&quot;, req);<br>    }</pre><pre>    private ResponseEntity&lt;ProblemDetail&gt; problem(<br>        HttpStatus status, String type, String detail, HttpServletRequest req<br>    ) {<br>        ProblemDetail body = new ProblemDetail(<br>            BASE_TYPE + type, status.getReasonPhrase(),<br>            status.value(), detail, req.getRequestURI(),<br>            Instant.now(), Map.of()<br>        );<br>        return ResponseEntity.status(status)<br>            .contentType(MediaType.APPLICATION_PROBLEM_JSON)<br>            .body(body);<br>    }<br>}</pre><p>Response example:</p><pre>{<br>  &quot;type&quot;: &quot;https://api.yourdomain.com/errors/validation-error&quot;,<br>  &quot;title&quot;: &quot;Validation Failed&quot;,<br>  &quot;status&quot;: 422,<br>  &quot;detail&quot;: &quot;One or more fields failed validation&quot;,<br>  &quot;instance&quot;: &quot;/api/v1/users&quot;,<br>  &quot;timestamp&quot;: &quot;2025-04-01T10:00:00Z&quot;,<br>  &quot;violations&quot;: [<br>    { &quot;field&quot;: &quot;email&quot;, &quot;message&quot;: &quot;must be a valid email&quot;, &quot;rejectedValue&quot;: &quot;not-an-email&quot; },<br>    { &quot;field&quot;: &quot;age&quot;,   &quot;message&quot;: &quot;must be at least 18&quot;,   &quot;rejectedValue&quot;: 15 }<br>  ]<br>}</pre><p>Note the Content-Type: application/problem+json — this is part of the RFC 7807 standard.</p><h3>5. Request Validation — A Layered Strategy</h3><p>Validation should happen at multiple layers, not just one.</p><pre>HTTP Layer   → Content-Type, body size limits<br>Controller   → @Valid with Bean Validation (format, null checks, regex)<br>Service      → Business rule validation (conflicts, state checks)<br>Database     → Unique constraints, foreign keys, not-null</pre><h3>Request DTO — Complete Example</h3><pre>public record CreateOrderRequest(</pre><pre>    @NotNull(message = &quot;Customer ID is required&quot;)<br>    UUID customerId,</pre><pre>    @NotEmpty(message = &quot;Order must contain at least one item&quot;)<br>    @Size(max = 50, message = &quot;Order cannot exceed 50 items&quot;)<br>    @Valid<br>    List&lt;OrderItemRequest&gt; items,</pre><pre>    @Valid<br>    ShippingAddressRequest shippingAddress,</pre><pre>    @NotNull<br>    CurrencyCode currency,</pre><pre>    @FutureOrPresent<br>    LocalDate requestedDeliveryDate</pre><pre>) {}</pre><pre>public record OrderItemRequest(</pre><pre>    @NotNull<br>    UUID productId,</pre><pre>    @NotNull @Min(1) @Max(999)<br>    Integer quantity,</pre><pre>    // Optional — server determines authoritative price; never trust client-supplied price<br>    @DecimalMin(&quot;0.01&quot;)<br>    BigDecimal unitPrice</pre><pre>) {}</pre><h3>Business Rule Validation — In the Service Layer</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    @Transactional<br>    public OrderDTO create(CreateOrderRequest request, String idempotencyKey) {</pre><pre>        // Rule: customer must be active<br>        Customer customer = customerRepository.findById(request.customerId())<br>            .filter(Customer::isActive)<br>            .orElseThrow(() -&gt; new BusinessRuleViolationException(<br>                &quot;Customer is not active or does not exist: &quot; + request.customerId()<br>            ));</pre><pre>        // Rule: all products must have sufficient stock<br>        request.items().forEach(item -&gt; {<br>            if (!inventoryService.isAvailable(item.productId(), item.quantity())) {<br>                throw new BusinessRuleViolationException(<br>                    &quot;Insufficient stock for product: &quot; + item.productId()<br>                );<br>            }<br>        });</pre><pre>        // ... order creation logic<br>    }<br>}</pre><h3>6. Pagination, Cursor-Based Paging, and Filtering</h3><h3>Offset vs Cursor Pagination</h3><p><strong>Offset Pagination</strong> (page=2&amp;size=20) is simple but breaks at scale:</p><pre>-- For page=100, size=20, the database reads 2020 rows and discards 2000<br>SELECT * FROM orders ORDER BY created_at DESC LIMIT 20 OFFSET 2000;</pre><p>Additionally, if new records are inserted during pagination, the same record can appear on two pages or records can be skipped entirely.</p><p><strong>Cursor Pagination</strong> solves these problems:</p><pre>public record CursorPageRequest(<br>    @Min(1) @Max(100) int size,<br>    String cursor,            // base64-encoded opaque token<br>    CursorDirection direction<br>) {}</pre><pre>public record CursorPage&lt;T&gt;(<br>    List&lt;T&gt; content,<br>    String nextCursor,<br>    String previousCursor,<br>    boolean hasNext,<br>    boolean hasPrevious<br>) {}</pre><pre>public CursorPage&lt;OrderDTO&gt; findWithCursor(CursorPageRequest request, OrderFilter filter) {<br>    Instant cursorTime = request.cursor() != null<br>        ? decodeCursor(request.cursor())<br>        : Instant.now();</pre><pre>    List&lt;Order&gt; orders = orderRepository.findByCursor(<br>        filter, cursorTime, request.direction(), request.size() + 1<br>    );</pre><pre>    boolean hasMore = orders.size() &gt; request.size();<br>    if (hasMore) orders = orders.subList(0, request.size());</pre><pre>    return new CursorPage&lt;&gt;(<br>        orders.stream().map(orderMapper::toDTO).toList(),<br>        hasMore ? encodeCursor(orders.getLast().getCreatedAt()) : null,<br>        request.cursor(),<br>        hasMore,<br>        request.cursor() != null<br>    );<br>}</pre><h3>Type-Safe Filtering with Specifications</h3><pre>public class OrderSpecifications {</pre><pre>    public static Specification&lt;Order&gt; hasStatus(OrderStatus status) {<br>        return (root, q, cb) -&gt;<br>            status == null ? null : cb.equal(root.get(&quot;status&quot;), status);<br>    }</pre><pre>    public static Specification&lt;Order&gt; belongsToCustomer(UUID customerId) {<br>        return (root, q, cb) -&gt;<br>            customerId == null ? null : cb.equal(root.get(&quot;customerId&quot;), customerId);<br>    }</pre><pre>    public static Specification&lt;Order&gt; createdBetween(Instant from, Instant to) {<br>        return (root, q, cb) -&gt; {<br>            if (from == null &amp;&amp; to == null) return null;<br>            if (from == null) return cb.lessThanOrEqualTo(root.get(&quot;createdAt&quot;), to);<br>            if (to == null)   return cb.greaterThanOrEqualTo(root.get(&quot;createdAt&quot;), from);<br>            return cb.between(root.get(&quot;createdAt&quot;), from, to);<br>        };<br>    }<br>}</pre><h3>7. DTO Design, Projections, and CQRS Separation</h3><h3>Multiple DTOs Per Entity</h3><pre>// List view — lightweight<br>public record OrderSummaryDTO(<br>    UUID id, String status, BigDecimal totalAmount,<br>    int itemCount, Instant createdAt<br>) {}</pre><pre>// Detail view — with relationships<br>public record OrderDetailDTO(<br>    UUID id, String status,<br>    CustomerSummaryDTO customer,<br>    List&lt;OrderItemDTO&gt; items,<br>    ShippingAddressDTO shippingAddress,<br>    BigDecimal subtotal, BigDecimal tax, BigDecimal totalAmount,<br>    Instant createdAt, Instant updatedAt<br>) {}</pre><pre>// Admin view — with internal fields<br>public record OrderAdminDTO(<br>    UUID id, String status,<br>    CustomerSummaryDTO customer,<br>    List&lt;OrderItemDTO&gt; items,<br>    BigDecimal totalAmount,<br>    String internalNotes,<br>    UUID assignedAgentId,<br>    String fraudScore,<br>    Instant createdAt<br>) {}</pre><h3>CQRS — Separate Read and Write Services</h3><pre>// Command side — transaction management, domain logic<br>@Service<br>@Transactional<br>public class OrderCommandService {<br>    public OrderDTO create(CreateOrderRequest request) { ... }<br>    public OrderDTO cancel(UUID id, CancelOrderRequest request) { ... }<br>}</pre><pre>// Query side — read-only, optimized queries<br>@Service<br>@Transactional(readOnly = true)<br>public class OrderQueryService {<br>    public OrderDetailDTO findById(UUID id) { ... }<br>    public CursorPage&lt;OrderSummaryDTO&gt; findAll(OrderFilter filter, CursorPageRequest page) { ... }<br>    public OrderStatisticsDTO getStatistics(UUID customerId, YearMonth period) { ... }<br>}</pre><h3>8. Optimistic Locking and Concurrency Control</h3><p>What happens when two users try to update the same record simultaneously? Optimistic locking catches this conflict at the application level rather than relying on database locks.</p><h3>Version Field on the Entity</h3><pre>@Entity<br>public class Order {</pre><pre>    @Id<br>    private UUID id;</pre><pre>    @Version<br>    private Long version;  // Managed automatically by JPA</pre><pre>    private OrderStatus status;<br>    private BigDecimal totalAmount;<br>}</pre><h3>Include Version in Responses</h3><pre>public record OrderDTO(<br>    UUID id,<br>    String status,<br>    BigDecimal totalAmount,<br>    Long version,    // Client must echo this back in PATCH/PUT requests<br>    Instant updatedAt<br>) {}</pre><h3>Enforcing the Expected Version</h3><pre>@PatchMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;OrderDTO&gt; patch(<br>    @PathVariable UUID id,<br>    @RequestHeader(&quot;If-Match&quot;) String eTag,<br>    @Valid @RequestBody PatchOrderRequest request<br>) {<br>    Long expectedVersion = parseETag(eTag);<br>    return ResponseEntity.ok(orderService.patch(id, expectedVersion, request));<br>}</pre><pre>@Transactional<br>public OrderDTO patch(UUID id, Long expectedVersion, PatchOrderRequest request) {<br>    Order order = orderRepository.findById(id)<br>        .orElseThrow(() -&gt; new ResourceNotFoundException(&quot;Order not found: &quot; + id));</pre><pre>    if (!order.getVersion().equals(expectedVersion)) {<br>        throw new OptimisticLockingFailureException(<br>            &quot;Order was modified by another request. Current version: &quot; + order.getVersion()<br>        );<br>    }</pre><pre>    // ... apply changes<br>    return orderMapper.toDTO(orderRepository.save(order));<br>}</pre><p>On conflict, the client receives 409 Conflict, fetches the latest version, and retries.</p><h3>9. Idempotency Keys — Making POST Safe</h3><p>Network interruptions happen in production. Critical POST operations like order creation or payments must be safely retryable.</p><pre>Client → POST /orders [Idempotency-Key: uuid-abc] → Server (success, 201)<br>Client → No response received (timeout)<br>Client → POST /orders [Idempotency-Key: uuid-abc] → Server (same key, 201 + cached response)</pre><h3>Implementation</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class IdempotencyService {</pre><pre>    private final IdempotencyKeyRepository repository;<br>    private final ObjectMapper objectMapper;</pre><pre>    public &lt;T&gt; Optional&lt;ResponseEntity&lt;T&gt;&gt; findCachedResponse(String key, Class&lt;T&gt; type) {<br>        return repository.findByKey(key)<br>            .map(record -&gt; {<br>                T body = objectMapper.convertValue(record.responseBody(), type);<br>                return ResponseEntity.status(record.httpStatus()).body(body);<br>            });<br>    }</pre><pre>    public void store(String key, int status, Object responseBody) {<br>        repository.save(new IdempotencyRecord(<br>            key, status, responseBody,<br>            Instant.now().plusSeconds(86400)  // 24-hour TTL<br>        ));<br>    }<br>}</pre><pre>@PostMapping(&quot;/orders&quot;)<br>public ResponseEntity&lt;OrderDTO&gt; create(<br>    @Valid @RequestBody CreateOrderRequest request,<br>    @RequestHeader(value = &quot;Idempotency-Key&quot;, required = false) String idempotencyKey<br>) {<br>    if (idempotencyKey != null) {<br>        Optional&lt;ResponseEntity&lt;OrderDTO&gt;&gt; cached =<br>            idempotencyService.findCachedResponse(idempotencyKey, OrderDTO.class);<br>        if (cached.isPresent()) return cached.get();<br>    }</pre><pre>    OrderDTO order = orderService.create(request);<br>    ResponseEntity&lt;OrderDTO&gt; response = ResponseEntity<br>        .created(URI.create(&quot;/api/v1/orders/&quot; + order.id()))<br>        .body(order);</pre><pre>    if (idempotencyKey != null) {<br>        idempotencyService.store(idempotencyKey, 201, order);<br>    }</pre><pre>    return response;<br>}</pre><h3>10. Conditional Requests — ETag and If-Modified-Since</h3><p>ETags eliminate unnecessary data transfer, reduce bandwidth consumption, and ensure cache consistency.</p><h3>Generating ETags</h3><pre>@GetMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;OrderDTO&gt; get(<br>    @PathVariable UUID id,<br>    @RequestHeader(value = &quot;If-None-Match&quot;, required = false) String ifNoneMatch<br>) {<br>    OrderDTO order = orderService.findById(id);<br>    String etag = &quot;\&quot;&quot; + order.version() + &quot;\&quot;&quot;;</pre><pre>    if (etag.equals(ifNoneMatch)) {<br>        return ResponseEntity.status(HttpStatus.NOT_MODIFIED).build(); // 304 — no body transferred<br>    }</pre><pre>    return ResponseEntity.ok()<br>        .eTag(etag)<br>        .lastModified(order.updatedAt())<br>        .body(order);<br>}</pre><p>The client sends If-None-Match: &quot;42&quot; on subsequent requests. If the resource hasn&#39;t changed, the server returns 304 Not Modified with no body.</p><h3>Shallow ETag Filter (Built-in Spring Support)</h3><pre>@Bean<br>public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {<br>    return new ShallowEtagHeaderFilter();<br>}</pre><p>This filter automatically computes the MD5 hash of the response body and attaches it as the ETag header.</p><h3>11. API Versioning — Strategy and Deprecation</h3><h3>Choosing a Strategy</h3><p>Strategy Example Pros Cons URI /api/v2/users Explicit, cache-friendly &quot;Pollutes&quot; the URL Header X-API-Version: 2 Clean URLs Cache complexity, low discoverability Media Type Accept: application/vnd.api.v2+json REST-pure Complex, limited tooling support</p><p><strong>Recommendation:</strong> URI versioning is the most pragmatic — strongest tooling support, easiest to debug.</p><h3>Breaking vs Non-Breaking Changes</h3><pre>Non-breaking (can be done without a new version):<br>  + Adding a new endpoint<br>  + Adding an optional field to an existing response<br>  + Adding an optional query parameter</pre><pre>Breaking (requires a new version):<br>  - Removing or renaming a field<br>  - Changing a field&#39;s type<br>  - Adding a required field to a request<br>  - Changing a status code<br>  - Restructuring a URL</pre><h3>Deprecation Lifecycle</h3><pre>@GetMapping(&quot;/users/{id}&quot;)<br>public ResponseEntity&lt;UserV1DTO&gt; getUserV1(@PathVariable UUID id) {<br>    return ResponseEntity.ok()<br>        .header(&quot;Deprecation&quot;, &quot;true&quot;)<br>        .header(&quot;Sunset&quot;, &quot;Mon, 01 Sep 2025 00:00:00 GMT&quot;)  // RFC 7231 date format<br>        .header(&quot;Link&quot;, &quot;&lt;/api/v2/users/&quot; + id + &quot;&gt;; rel=\&quot;successor-version\&quot;&quot;)<br>        .header(&quot;Warning&quot;, &quot;299 - \&quot;This endpoint is deprecated. Use /api/v2/users\&quot;&quot;)<br>        .body(userService.findByIdV1(id));<br>}</pre><h3>12. Authentication, Authorization, and Fine-Grained Access</h3><h3>JWT Token Structure</h3><pre>@Service<br>public class JwtService {</pre><pre>    public String generateToken(User user) {<br>        return Jwts.builder()<br>            .subject(user.getId().toString())<br>            .claim(&quot;email&quot;,       user.getEmail())<br>            .claim(&quot;roles&quot;,       user.getRoles())<br>            .claim(&quot;permissions&quot;, user.getPermissions())  // fine-grained<br>            .issuedAt(new Date())<br>            .expiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))<br>            .signWith(getSigningKey(), SignatureAlgorithm.HS256)<br>            .compact();<br>    }<br>}</pre><h3>Resource-Level Ownership Checks</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderAuthorizationService {</pre><pre>    public void assertCanRead(UUID orderId, SecurityContext ctx) {<br>        User user = (User) ctx.getAuthentication().getPrincipal();<br>        if (user.hasRole(&quot;ADMIN&quot;)) return;</pre><pre>        Order order = orderRepository.findById(orderId)<br>            .orElseThrow(() -&gt; new ResourceNotFoundException(&quot;Order not found: &quot; + orderId));</pre><pre>        if (!order.getCustomerId().equals(user.getId())) {<br>            // Return 404 instead of 403 to avoid leaking resource existence<br>            throw new ResourceNotFoundException(&quot;Order not found: &quot; + orderId);<br>        }<br>    }<br>}</pre><h3>Method-Level Security</h3><pre>@Configuration<br>@EnableMethodSecurity<br>public class SecurityConfig { ... }</pre><pre>@RestController<br>public class OrderController {</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;) or @orderAuthorizationService.canRead(#id, authentication)&quot;)<br>    public ResponseEntity&lt;OrderDetailDTO&gt; get(@PathVariable UUID id) { ... }</pre><pre>    @DeleteMapping(&quot;/{id}&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>    public ResponseEntity&lt;Void&gt; delete(@PathVariable UUID id) { ... }<br>}</pre><h3>13. CORS and Security Headers</h3><h3>CORS — Environment-Specific Configuration</h3><pre>@Configuration<br>public class CorsConfig implements WebMvcConfigurer {</pre><pre>    @Value(&quot;${app.cors.allowed-origins}&quot;)<br>    private List&lt;String&gt; allowedOrigins;</pre><pre>    @Override<br>    public void addCorsMappings(CorsRegistry registry) {<br>        registry.addMapping(&quot;/api/**&quot;)<br>            .allowedOrigins(allowedOrigins.toArray(String[]::new))<br>            .allowedMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;)<br>            .allowedHeaders(&quot;Authorization&quot;, &quot;Content-Type&quot;,<br>                           &quot;Idempotency-Key&quot;, &quot;If-Match&quot;, &quot;If-None-Match&quot;)<br>            .exposedHeaders(&quot;ETag&quot;, &quot;Location&quot;, &quot;X-Trace-Id&quot;,<br>                           &quot;X-Rate-Limit-Remaining&quot;, &quot;Retry-After&quot;)<br>            .allowCredentials(true)<br>            .maxAge(3600);<br>    }<br>}</pre><h3>Security Headers</h3><pre>@Component<br>public class SecurityHeadersFilter extends OncePerRequestFilter {</pre><pre>    @Override<br>    protected void doFilterInternal(<br>        HttpServletRequest req, HttpServletResponse res, FilterChain chain<br>    ) throws ServletException, IOException {</pre><pre>        res.setHeader(&quot;X-Frame-Options&quot;,         &quot;DENY&quot;);<br>        res.setHeader(&quot;X-Content-Type-Options&quot;,  &quot;nosniff&quot;);<br>        res.setHeader(&quot;X-XSS-Protection&quot;,        &quot;1; mode=block&quot;);<br>        res.setHeader(&quot;Referrer-Policy&quot;,         &quot;strict-origin-when-cross-origin&quot;);<br>        res.setHeader(&quot;Content-Security-Policy&quot;, &quot;default-src &#39;self&#39;&quot;);<br>        res.setHeader(&quot;Strict-Transport-Security&quot;,&quot;max-age=31536000; includeSubDomains&quot;);</pre><pre>        chain.doFilter(req, res);<br>    }<br>}</pre><h3>14. Rate Limiting and Throttling Strategies</h3><h3>Sliding Window Rate Limiter with Redis</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class RedisRateLimiter {</pre><pre>    private final RedisTemplate&lt;String, String&gt; redisTemplate;</pre><pre>    public RateLimitResult tryConsume(String key, int limit, Duration window) {<br>        String redisKey = &quot;rate_limit:&quot; + key;<br>        long now = Instant.now().toEpochMilli();<br>        long windowStart = now - window.toMillis();</pre><pre>        // Remove entries outside the current window<br>        redisTemplate.opsForZSet().removeRangeByScore(redisKey, 0, windowStart);</pre><pre>        Long count = redisTemplate.opsForZSet().zCard(redisKey);<br>        long remaining = Math.max(0, limit - (count == null ? 0 : count));</pre><pre>        if (remaining &lt;= 0) {<br>            Set&lt;ZSetOperations.TypedTuple&lt;String&gt;&gt; oldest =<br>                redisTemplate.opsForZSet().rangeWithScores(redisKey, 0, 0);<br>            long retryAfterMs = oldest.isEmpty() ? window.toMillis()<br>                : (long)(oldest.iterator().next().getScore()) + window.toMillis() - now;</pre><pre>            return RateLimitResult.exceeded(Duration.ofMillis(retryAfterMs));<br>        }</pre><pre>        redisTemplate.opsForZSet().add(redisKey, UUID.randomUUID().toString(), now);<br>        redisTemplate.expire(redisKey, window);</pre><pre>        return RateLimitResult.allowed(remaining);<br>    }<br>}</pre><pre>@Component<br>@RequiredArgsConstructor<br>public class RateLimitingFilter extends OncePerRequestFilter {</pre><pre>    private final RedisRateLimiter rateLimiter;<br>    private final AuthenticationService authService;</pre><pre>    @Override<br>    protected void doFilterInternal(<br>        HttpServletRequest req, HttpServletResponse res, FilterChain chain<br>    ) throws ServletException, IOException {</pre><pre>        String key = authService.getCurrentUserId()<br>            .map(id -&gt; &quot;user:&quot; + id)<br>            .orElse(&quot;ip:&quot; + req.getRemoteAddr());</pre><pre>        RateLimitResult result = rateLimiter.tryConsume(key, 100, Duration.ofMinutes(1));</pre><pre>        res.addHeader(&quot;X-Rate-Limit-Limit&quot;,     &quot;100&quot;);<br>        res.addHeader(&quot;X-Rate-Limit-Remaining&quot;, String.valueOf(result.remaining()));</pre><pre>        if (result.isExceeded()) {<br>            res.addHeader(&quot;Retry-After&quot;, String.valueOf(result.retryAfter().getSeconds()));<br>            res.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());<br>            res.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);<br>            res.getWriter().write(&quot;&quot;&quot;<br>                {<br>                  &quot;type&quot;: &quot;https://api.yourdomain.com/errors/rate-limit-exceeded&quot;,<br>                  &quot;title&quot;: &quot;Too Many Requests&quot;,<br>                  &quot;status&quot;: 429,<br>                  &quot;detail&quot;: &quot;Rate limit exceeded. Retry after %d seconds.&quot;<br>                }<br>                &quot;&quot;&quot;.formatted(result.retryAfter().getSeconds()));<br>            return;<br>        }</pre><pre>        chain.doFilter(req, res);<br>    }<br>}</pre><h3>15. The N+1 Problem and Database Optimization</h3><h3>Detecting N+1</h3><pre>// With spring.jpa.show-sql=true, you&#39;ll see this dangerous pattern:<br>// SELECT * FROM orders WHERE ...        ← 1 query<br>// SELECT * FROM order_items WHERE id=1  ← N queries (one per order)<br>// SELECT * FROM order_items WHERE id=2<br>// ...</pre><h3>Solution 1 — JOIN FETCH</h3><pre>@Query(&quot;&quot;&quot;<br>    SELECT DISTINCT o FROM Order o<br>    LEFT JOIN FETCH o.items i<br>    LEFT JOIN FETCH i.product<br>    WHERE o.customerId = :customerId<br>    &quot;&quot;&quot;)<br>List&lt;Order&gt; findAllWithItemsByCustomer(@Param(&quot;customerId&quot;) UUID customerId);</pre><h3>Solution 2 — @EntityGraph</h3><pre>@EntityGraph(attributePaths = {&quot;items&quot;, &quot;items.product&quot;, &quot;customer&quot;})<br>@Query(&quot;SELECT o FROM Order o WHERE o.id = :id&quot;)<br>Optional&lt;Order&gt; findByIdWithGraph(@Param(&quot;id&quot;) UUID id);</pre><h3>Solution 3 — Batch Size</h3><pre>@Entity<br>public class Order {<br>    @OneToMany(mappedBy = &quot;order&quot;)<br>    @BatchSize(size = 30)  // Hibernate loads in batches of 30, reducing N+1 to N/30+1<br>    private List&lt;OrderItem&gt; items;<br>}</pre><h3>Solution 4 — Interface Projection (Fetch Only What You Need)</h3><pre>public interface OrderSummaryProjection {<br>    UUID getId();<br>    String getStatus();<br>    BigDecimal getTotalAmount();<br>    Instant getCreatedAt();<br>}</pre><pre>List&lt;OrderSummaryProjection&gt; findByCustomerId(UUID customerId, Pageable pageable);</pre><p>This fetches only the required columns without loading the full entity.</p><h3>16. Observability — Logging, Metrics, and Distributed Tracing</h3><h3>Structured Logging with MDC</h3><pre>@Component<br>@Slf4j<br>public class ObservabilityFilter extends OncePerRequestFilter {</pre><pre>    @Override<br>    protected void doFilterInternal(<br>        HttpServletRequest req, HttpServletResponse res, FilterChain chain<br>    ) throws ServletException, IOException {</pre><pre>        String traceId = Optional.ofNullable(req.getHeader(&quot;X-Trace-Id&quot;))<br>            .orElse(UUID.randomUUID().toString());<br>        String spanId = UUID.randomUUID().toString().substring(0, 8);</pre><pre>        MDC.put(&quot;traceId&quot;,   traceId);<br>        MDC.put(&quot;spanId&quot;,    spanId);<br>        MDC.put(&quot;method&quot;,    req.getMethod());<br>        MDC.put(&quot;path&quot;,      req.getRequestURI());<br>        MDC.put(&quot;userAgent&quot;, req.getHeader(&quot;User-Agent&quot;));</pre><pre>        res.setHeader(&quot;X-Trace-Id&quot;, traceId);<br>        res.setHeader(&quot;X-Span-Id&quot;,  spanId);</pre><pre>        long start = System.currentTimeMillis();<br>        try {<br>            chain.doFilter(req, res);<br>        } finally {<br>            long duration = System.currentTimeMillis() - start;<br>            MDC.put(&quot;status&quot;,   String.valueOf(res.getStatus()));<br>            MDC.put(&quot;duration&quot;, duration + &quot;ms&quot;);<br>            log.info(&quot;HTTP {} {} → {} ({}ms)&quot;,<br>                req.getMethod(), req.getRequestURI(), res.getStatus(), duration);<br>            MDC.clear();<br>        }<br>    }<br>}</pre><h3>Custom Metrics with Micrometer</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final MeterRegistry meterRegistry;</pre><pre>    public OrderDTO create(CreateOrderRequest request) {<br>        return Timer.builder(&quot;order.creation.duration&quot;)<br>            .tag(&quot;currency&quot;, request.currency().toString())<br>            .register(meterRegistry)<br>            .record(() -&gt; {<br>                OrderDTO order = doCreate(request);<br>                meterRegistry.counter(&quot;orders.created&quot;,<br>                    &quot;status&quot;,   &quot;success&quot;,<br>                    &quot;currency&quot;, request.currency().toString()<br>                ).increment();<br>                return order;<br>            });<br>    }<br>}</pre><h3>Actuator + Prometheus</h3><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: health, info, metrics, prometheus<br>  endpoint:<br>    health:<br>      show-details: when-authorized<br>  metrics:<br>    export:<br>      prometheus:<br>        enabled: true</pre><pre>@Component<br>@RequiredArgsConstructor<br>public class PaymentGatewayHealthIndicator implements HealthIndicator {</pre><pre>    private final ExternalPaymentService paymentService;</pre><pre>    @Override<br>    public Health health() {<br>        try {<br>            paymentService.ping();<br>            return Health.up()<br>                .withDetail(&quot;payment-gateway&quot;, &quot;reachable&quot;)<br>                .build();<br>        } catch (Exception e) {<br>            return Health.down()<br>                .withDetail(&quot;payment-gateway&quot;, &quot;unreachable&quot;)<br>                .withException(e)<br>                .build();<br>        }<br>    }<br>}</pre><h3>17. OpenAPI and Contract-First Development</h3><h3>Controller Annotations</h3><pre>@Tag(name = &quot;Orders&quot;, description = &quot;Order management operations&quot;)<br>@RestController<br>@RequestMapping(&quot;/api/v1/orders&quot;)<br>public class OrderController {</pre><pre>    @Operation(<br>        summary = &quot;Create a new order&quot;,<br>        description = &quot;Creates a new order. Supports idempotent creation via Idempotency-Key header.&quot;<br>    )<br>    @ApiResponses({<br>        @ApiResponse(responseCode = &quot;201&quot;, description = &quot;Order created&quot;,<br>            headers = @Header(name = &quot;Location&quot;, description = &quot;URL of the created resource&quot;)),<br>        @ApiResponse(responseCode = &quot;422&quot;, description = &quot;Validation failed&quot;,<br>            content = @Content(mediaType = &quot;application/problem+json&quot;,<br>                schema = @Schema(implementation = ProblemDetail.class))),<br>        @ApiResponse(responseCode = &quot;409&quot;, description = &quot;Duplicate idempotency key&quot;)<br>    })<br>    @PostMapping<br>    public ResponseEntity&lt;OrderDTO&gt; create(<br>        @Parameter(description = &quot;Unique key for idempotent request processing&quot;)<br>        @RequestHeader(value = &quot;Idempotency-Key&quot;, required = false) String idempotencyKey,<br>        @Valid @RequestBody CreateOrderRequest request<br>    ) { ... }<br>}</pre><h3>Schema Annotations</h3><pre>@Schema(description = &quot;Request payload for creating a new order&quot;)<br>public record CreateOrderRequest(</pre><pre>    @Schema(description = &quot;Customer UUID&quot;,<br>            example = &quot;550e8400-e29b-41d4-a716-446655440000&quot;)<br>    @NotNull UUID customerId,</pre><pre>    @Schema(description = &quot;Order line items, minimum 1&quot;)<br>    @NotEmpty @Valid List&lt;OrderItemRequest&gt; items,</pre><pre>    @Schema(description = &quot;ISO 4217 currency code&quot;, example = &quot;USD&quot;,<br>            allowableValues = {&quot;USD&quot;, &quot;EUR&quot;, &quot;TRY&quot;})<br>    @NotNull CurrencyCode currency</pre><pre>) {}</pre><h3>18. Advanced API Layer on the React Side</h3><h3>Axios Instance with Token Refresh Queue</h3><pre>// src/lib/apiClient.js<br>import axios from &#39;axios&#39;;<br>import { authStore } from &#39;@/stores/authStore&#39;;</pre><pre>let isRefreshing = false;<br>let failedQueue = [];</pre><pre>const processQueue = (error, token = null) =&gt; {<br>  failedQueue.forEach(p =&gt; error ? p.reject(error) : p.resolve(token));<br>  failedQueue = [];<br>};</pre><pre>const apiClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_BASE_URL,<br>  timeout: 15_000,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>});</pre><pre>apiClient.interceptors.request.use(config =&gt; {<br>  const token = authStore.getAccessToken();<br>  if (token) config.headers.Authorization = `Bearer ${token}`;</pre><pre>  // Auto-attach idempotency key for mutating methods<br>  if ([&#39;post&#39;, &#39;put&#39;, &#39;patch&#39;].includes(config.method)) {<br>    config.headers[&#39;Idempotency-Key&#39;] ??= crypto.randomUUID();<br>  }</pre><pre>  return config;<br>});</pre><pre>apiClient.interceptors.response.use(<br>  response =&gt; response,<br>  async error =&gt; {<br>    const originalRequest = error.config;</pre><pre>    if (error.response?.status === 401 &amp;&amp; !originalRequest._retry) {<br>      if (isRefreshing) {<br>        return new Promise((resolve, reject) =&gt; {<br>          failedQueue.push({ resolve, reject });<br>        }).then(token =&gt; {<br>          originalRequest.headers.Authorization = `Bearer ${token}`;<br>          return apiClient(originalRequest);<br>        });<br>      }</pre><pre>      originalRequest._retry = true;<br>      isRefreshing = true;</pre><pre>      try {<br>        const newToken = await authStore.refreshToken();<br>        processQueue(null, newToken);<br>        originalRequest.headers.Authorization = `Bearer ${newToken}`;<br>        return apiClient(originalRequest);<br>      } catch (refreshError) {<br>        processQueue(refreshError, null);<br>        authStore.logout();<br>        return Promise.reject(refreshError);<br>      } finally {<br>        isRefreshing = false;<br>      }<br>    }</pre><pre>    return Promise.reject(error);<br>  }<br>);</pre><pre>export default apiClient;</pre><h3>Optimistic Updates with React Query</h3><pre>export const useCancelOrder = () =&gt; {<br>  const queryClient = useQueryClient();</pre><pre>  return useMutation({<br>    mutationFn: ({ id }) =&gt; orderService.cancel(id),</pre><pre>    // 1. Update UI immediately before the request completes<br>    onMutate: async ({ id }) =&gt; {<br>      await queryClient.cancelQueries({ queryKey: [&#39;orders&#39;, id] });<br>      const previousOrder = queryClient.getQueryData([&#39;orders&#39;, id]);</pre><pre>      queryClient.setQueryData([&#39;orders&#39;, id], old =&gt; ({<br>        ...old,<br>        status: &#39;CANCELLED&#39;,<br>      }));</pre><pre>      return { previousOrder };<br>    },</pre><pre>    // 2. Roll back on failure<br>    onError: (error, { id }, context) =&gt; {<br>      queryClient.setQueryData([&#39;orders&#39;, id], context.previousOrder);<br>    },</pre><pre>    // 3. Sync with server after success or failure<br>    onSettled: (data, error, { id }) =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&#39;orders&#39;, id] });<br>      queryClient.invalidateQueries({ queryKey: [&#39;orders&#39;] });<br>    },<br>  });<br>};</pre><h3>Error Boundary for API Errors</h3><pre>// src/components/ApiErrorBoundary.jsx<br>import { useRouteError } from &#39;react-router-dom&#39;;</pre><pre>export function ApiErrorBoundary() {<br>  const error = useRouteError();<br>  const problem = error?.response?.data;</pre><pre>  if (problem?.status === 404) return &lt;NotFoundPage /&gt;;<br>  if (problem?.status === 403) return &lt;ForbiddenPage /&gt;;</pre><pre>  return (<br>    &lt;ErrorPage<br>      title={problem?.title ?? &#39;An error occurred&#39;}<br>      detail={problem?.detail}<br>      traceId={error?.response?.headers?.[&#39;x-trace-id&#39;]}<br>    /&gt;<br>  );<br>}</pre><h3>19. Production Readiness Checklist</h3><h3>API Design and Contract</h3><ul><li>[ ] HTTP methods are correct from both semantic and idempotency perspectives</li><li>[ ] URLs are consistent, lowercase, noun-based, and hierarchical</li><li>[ ] RFC 7807 Problem Details implemented (application/problem+json)</li><li>[ ] All endpoints share the same error response structure</li><li>[ ] ETag and conditional request support on critical read endpoints</li><li>[ ] Idempotency key support on POST endpoints</li><li>[ ] Versioning strategy defined before production; deprecation headers active</li></ul><h3>Data and Performance</h3><ul><li>[ ] All list endpoints are paginated (cursor or offset)</li><li>[ ] N+1 queries identified and eliminated</li><li>[ ] DTO layer enforced — entities never returned directly</li><li>[ ] Optimistic locking applied on critical resources</li><li>[ ] Read-only transactions used in query services</li></ul><h3>Security</h3><ul><li>[ ] JWT correctly configured (short TTL, refresh token rotation)</li><li>[ ] Resource-level ownership checks in place</li><li>[ ] CORS configured per environment — no wildcard</li><li>[ ] Security headers active (HSTS, CSP, X-Frame-Options)</li><li>[ ] Rate limiting in place, Redis-backed for distributed environments</li><li>[ ] Sensitive fields excluded from all responses</li><li>[ ] HTTPS enforced, HTTP automatically redirected</li></ul><h3>Observability</h3><ul><li>[ ] Unique traceId generated per request, included in response headers</li><li>[ ] Structured logging configured (JSON format recommended)</li><li>[ ] Micrometer + Prometheus metrics active</li><li>[ ] Custom health indicators monitor external dependencies</li><li>[ ] OpenAPI documentation kept in sync with code</li><li>[ ] Alerting configured for critical metrics (error rate, latency, saturation)</li></ul><p><em>References: </em><a href="https://datatracker.ietf.org/doc/html/rfc7807"><em>RFC 7807 — Problem Details</em></a><em> · </em><a href="https://datatracker.ietf.org/doc/html/rfc7232"><em>RFC 7232 — Conditional Requests</em></a><em> · </em><a href="https://datatracker.ietf.org/doc/html/rfc7231"><em>RFC 7231 — HTTP Semantics</em></a><em> · </em><a href="https://cloud.google.com/apis/design"><em>Google Cloud API Design Guide</em></a><em> · </em><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/"><em>Spring Boot Docs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b9b432ca165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Tasarımı Rehberi]]></title>
            <link>https://medium.com/@sahin.ilyd/rest-api-geli%C5%9Ftirirken-yapt%C4%B1%C4%9F%C4%B1m-hatalar-ve-%C3%B6%C4%9Frendiklerim-c956993714ce?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/c956993714ce</guid>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 10:19:09 GMT</pubDate>
            <atom:updated>2026-04-01T10:44:30.644Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Bu yazı temel CRUD’un ötesine geçer. HTTP semantiği, idempotency, optimistic locking, N+1 sorunları, cache stratejileri, distributed tracing ve observability gibi konuları Spring Boot ve React ekosistemi üzerinden ele alır.</em></blockquote><h3>İçindekiler</h3><ol><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#1-http-semanti%C4%9Fi-ve-idempotency">HTTP Semantiği ve İdempotency</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#2-url-tasar%C4%B1m%C4%B1-ve-kaynak-modelleme">URL Tasarımı ve Kaynak Modelleme</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#3-http-status-codes--n%C3%BCanslar-ve-tuzaklar">HTTP Status Codes — Nüanslar ve Tuzaklar</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#4-standart-hata-yap%C4%B1s%C4%B1-ve-problem-details-rfc-7807">Standart Hata Yapısı ve Problem Details (RFC 7807)</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#5-request-validation--katmanl%C4%B1-strateji">Request Validation — Katmanlı Strateji</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#6-pagination-cursor-based-sayfalama-ve-filtering">Pagination, Cursor-based Sayfalama ve Filtering</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#7-dto-tasar%C4%B1m%C4%B1-projeksiyon-ve-cqrs-ayr%C4%B1m%C4%B1">DTO Tasarımı, Projeksiyon ve CQRS Ayrımı</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#8-optimistic-locking-ve-concurrency-kontrol%C3%BC">Optimistic Locking ve Concurrency Kontrolü</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#9-idempotency-keys--post-i%CC%87steklerini-g%C3%BCvenli-yapmak">Idempotency Keys — POST İsteklerini Güvenli Yapmak</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#10-conditional-requests--etag-ve-if-modified-since">Conditional Requests — ETag ve If-Modified-Since</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#11-api-versiyonlama--strateji-ve-deprecation">API Versiyonlama — Strateji ve Deprecation</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#12-authentication-authorization-ve-fine-grained-eri%C5%9Fim">Authentication, Authorization ve Fine-Grained Erişim</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#13-cors-ve-g%C3%BCvenlik-headerlar%C4%B1">CORS ve Güvenlik Header’ları</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#14-rate-limiting-ve-throttling-stratejileri">Rate Limiting ve Throttling Stratejileri</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#15-n1-sorunu-ve-veritaban%C4%B1-optimizasyonu">N+1 Sorunu ve Veritabanı Optimizasyonu</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#16-observability--logging-metrics-ve-distributed-tracing">Observability — Logging, Metrics ve Distributed Tracing</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#17-openapi-ve-s%C3%B6zle%C5%9Fme-%C3%B6ncelikli-geli%C5%9Ftirme">OpenAPI ve Sözleşme Öncelikli Geliştirme</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#18-react-taraf%C4%B1nda-geli%C5%9Fmi%C5%9F-api-katman%C4%B1">React Tarafında Gelişmiş API Katmanı</a></li><li><a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#19-%C3%BCretim-ortam%C4%B1-kontrol-listesi">Üretim Ortamı Kontrol Listesi</a></li></ol><h3>1. HTTP Semantiği ve İdempotency</h3><p>HTTP metodları bir sözleşmedir. Bu sözleşmeyi ihlal etmek, proxy’lerin, CDN’lerin, yük dengeleyicilerin ve client’ların beklenmedik biçimde davranmasına yol açar.</p><h3>İdempotency Neden Kritik?</h3><p>Bir istek ağ kesintisi nedeniyle başarısız olduğunda, client yeniden denemeli midir? Bu sorunun cevabı metodun idempotent olup olmadığına bağlıdır.</p><pre>GET    /orders/123     → Her zaman yeniden denenebilir (safe + idempotent)<br>PUT    /orders/123     → Yeniden denenebilir (idempotent)<br>DELETE /orders/123     → Yeniden denenebilir (idempotent)<br>POST   /orders         → TEHLİKELİ — çift sipariş oluşabilir (not idempotent)<br>PATCH  /orders/123     → Dikkatli olunmalı — operasyona göre değişir</pre><h3>PATCH İdempotency Tuzağı</h3><pre>// PATCH ile gönderilecek iki farklı payload türü</pre><pre>// 1. Absolute value patch — idempotent, güvenli<br>{ &quot;status&quot;: &quot;CANCELLED&quot; }</pre><pre>// 2. Relative / delta patch — NOT idempotent, tehlikeli<br>{ &quot;quantity&quot;: { &quot;increment&quot;: 1 } }</pre><p>increment gibi göreli güncellemeler idempotent değildir. Aynı istek iki kez gönderilirse miktar iki kez artar. Bu tür operasyonlar için <a href="https://claude.ai/chat/77c30780-99ed-47f2-afd4-f7ad8347878e#9-idempotency-keys--post-i%CC%87steklerini-g%C3%BCvenli-yapmak">Section 9</a>&#39;da anlatılan idempotency key mekanizması kullanılmalıdır.</p><h3>Spring Boot’ta Tam CRUD Controller</h3><pre>@RestController<br>@RequestMapping(&quot;/api/v1/orders&quot;)<br>@RequiredArgsConstructor<br>@Validated<br>public class OrderController {</pre><pre>    private final OrderService orderService;</pre><pre>    @GetMapping<br>    public ResponseEntity&lt;PagedModel&lt;OrderDTO&gt;&gt; list(<br>        @Valid OrderFilter filter,<br>        @PageableDefault(size = 20, sort = &quot;createdAt&quot;, direction = DESC) Pageable pageable<br>    ) {<br>        return ResponseEntity.ok(orderService.findAll(filter, pageable));<br>    }</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; get(@PathVariable UUID id) {<br>        return ResponseEntity.ok(orderService.findById(id));<br>    }</pre><pre>    @PostMapping<br>    public ResponseEntity&lt;OrderDTO&gt; create(<br>        @Valid @RequestBody CreateOrderRequest request,<br>        @RequestHeader(value = &quot;Idempotency-Key&quot;, required = false) String idempotencyKey<br>    ) {<br>        OrderDTO order = orderService.create(request, idempotencyKey);<br>        return ResponseEntity<br>            .created(URI.create(&quot;/api/v1/orders/&quot; + order.id()))<br>            .body(order);<br>    }</pre><pre>    @PutMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; replace(<br>        @PathVariable UUID id,<br>        @Valid @RequestBody ReplaceOrderRequest request<br>    ) {<br>        return ResponseEntity.ok(orderService.replace(id, request));<br>    }</pre><pre>    @PatchMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; patch(<br>        @PathVariable UUID id,<br>        @Valid @RequestBody PatchOrderRequest request<br>    ) {<br>        return ResponseEntity.ok(orderService.patch(id, request));<br>    }</pre><pre>    @DeleteMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Void&gt; delete(@PathVariable UUID id) {<br>        orderService.delete(id);<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><h3>2. URL Tasarımı ve Kaynak Modelleme</h3><p>URL tasarımı bir mimari karardır. Yanlış bir tasarım, sonraki versiyonlarda yüksek maliyetli breaking change’lere yol açar.</p><h3>Kaynak Hiyerarşisi — Ne Zaman Flat, Ne Zaman Nested?</h3><pre># Derin nested yapı — kaçın<br>/users/{userId}/departments/{deptId}/teams/{teamId}/members/{memberId}/tasks/{taskId}</pre><pre># Flat + ilişki parametresi — tercih et<br>/tasks?memberId={memberId}&amp;teamId={teamId}</pre><pre># Mantıklı nested (2 seviye makul)<br>/orders/{orderId}/items<br>/users/{userId}/addresses</pre><p><strong>Kural:</strong> Alt kaynak üst kaynaksız anlam taşımıyorsa nested olabilir. Bağımsız yaşayabiliyorsa flat tutun.</p><h3>Eylem Endpoint’leri — RPC Tuzakları</h3><pre># Yanlış — HTTP metodunu görmezden geliyor<br>POST /orders/cancel         → hangi sipariş?<br>GET  /orders/sendEmail      → GET yan etki yaratıyor</pre><pre># Doğru — kaynak + alt-kaynak olarak model<br>POST /orders/{id}/cancellation<br>POST /orders/{id}/notifications</pre><pre># Ya da state machine yaklaşımı (daha iyi)<br>PATCH /orders/{id}<br>Body: { &quot;status&quot;: &quot;CANCELLED&quot; }</pre><h3>Query Parameter Standartları</h3><pre># Filtreleme<br>GET /products?category=electronics&amp;minPrice=100&amp;maxPrice=500</pre><pre># Sıralama — tek parametre, çoklu alan<br>GET /products?sort=price:asc,name:desc</pre><pre># Alanları seçme (sparse fieldsets)<br>GET /users?fields=id,name,email</pre><pre># Include / embed ilişkili kaynak<br>GET /orders?include=items,customer</pre><h3>3. HTTP Status Codes — Nüanslar ve Tuzaklar</h3><h3>Çoğunlukla Yanlış Kullanılan Kodlar</h3><p><strong>200 vs 201:</strong></p><pre>// Yanlış — kaynak oluştururken 200 dönmek<br>@PostMapping<br>public ResponseEntity&lt;UserDTO&gt; create(...) {<br>    return ResponseEntity.ok(userService.create(request)); // 200 ❌<br>}</pre><pre>// Doğru — 201 + Location header<br>@PostMapping<br>public ResponseEntity&lt;UserDTO&gt; create(...) {<br>    UserDTO user = userService.create(request);<br>    return ResponseEntity<br>        .created(URI.create(&quot;/api/v1/users/&quot; + user.id()))<br>        .body(user); // 201 ✅<br>}</pre><p><strong>401 vs 403:</strong></p><pre>401 Unauthorized → &quot;Kimliğini bilmiyorum, lütfen giriş yap&quot;<br>403 Forbidden    → &quot;Kimliğini biliyorum ama bu kaynağa erişim hakkın yok&quot;</pre><pre>Token eksik    → 401<br>Token süresi dolmuş → 401<br>Token geçerli ama yetki yok → 403</pre><p><strong>404 vs 403 — Bilgi Sızıntısı:</strong></p><pre>// Güvenlik tuzağı — kaynak var ama erişim yasak<br>// 403 dönmek kaynağın varlığını ifşa eder<br>if (!order.belongsTo(currentUser)) {<br>    throw new ForbiddenException(); // 403 → varlığı ifşa eder<br>}</pre><pre>// Daha güvenli — varlığı gizle<br>if (!order.belongsTo(currentUser)) {<br>    throw new ResourceNotFoundException(); // 404 → sessiz red<br>}</pre><p><strong>422 vs 400:</strong></p><pre>400 Bad Request          → Parse edilemeyen / yapısal hata (malformed JSON)<br>422 Unprocessable Entity → Parse edildi ama iş kuralı veya alan validasyonu başarısız</pre><h3>4. Standart Hata Yapısı ve Problem Details (RFC 7807)</h3><p>Kendi hata formatınızı icat etmek yerine endüstri standardı olan RFC 7807 Problem Details kullanın. Bu format Swagger, API Gateway’ler ve monitoring araçları tarafından tanınır.</p><h3>Problem Details Modeli</h3><pre>public record ProblemDetail(<br>    String type,       // URI — hata tipi dökümantasyonu<br>    String title,      // Kısa, insan okunabilir başlık<br>    int status,        // HTTP status kodu<br>    String detail,     // Bu isteğe özgü açıklama<br>    String instance,   // İsteği tanımlayan URI<br>    Instant timestamp,<br>    Map&lt;String, Object&gt; extensions // ek alanlar<br>) {<br>    public static Builder builder(HttpStatus status) {<br>        return new Builder(status);<br>    }</pre><pre>    public static final class Builder {<br>        // fluent builder implementasyonu<br>    }<br>}</pre><h3>Global Exception Handler — Tam Uygulama</h3><pre>@RestControllerAdvice<br>@Slf4j<br>public class GlobalExceptionHandler {</pre><pre>    private static final String BASE_TYPE = &quot;https://api.yourdomain.com/errors/&quot;;</pre><pre>    @ExceptionHandler(ResourceNotFoundException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleNotFound(<br>        ResourceNotFoundException ex, HttpServletRequest req<br>    ) {<br>        return problem(HttpStatus.NOT_FOUND, &quot;not-found&quot;,<br>            ex.getMessage(), req.getRequestURI());<br>    }</pre><pre>    @ExceptionHandler(BusinessRuleViolationException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleBusinessRule(<br>        BusinessRuleViolationException ex, HttpServletRequest req<br>    ) {<br>        return problem(HttpStatus.UNPROCESSABLE_ENTITY, &quot;business-rule-violation&quot;,<br>            ex.getMessage(), req.getRequestURI());<br>    }</pre><pre>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleValidation(<br>        MethodArgumentNotValidException ex, HttpServletRequest req<br>    ) {<br>        List&lt;FieldError&gt; fieldErrors = ex.getBindingResult()<br>            .getFieldErrors()<br>            .stream()<br>            .map(e -&gt; new FieldError(e.getField(), e.getDefaultMessage(), e.getRejectedValue()))<br>            .toList();</pre><pre>        ProblemDetail body = ProblemDetail.builder(HttpStatus.UNPROCESSABLE_ENTITY)<br>            .type(BASE_TYPE + &quot;validation-error&quot;)<br>            .title(&quot;Validation Failed&quot;)<br>            .detail(&quot;One or more fields failed validation&quot;)<br>            .instance(req.getRequestURI())<br>            .extension(&quot;violations&quot;, fieldErrors)<br>            .build();</pre><pre>        return ResponseEntity.unprocessableEntity().body(body);<br>    }</pre><pre>    @ExceptionHandler(OptimisticLockingFailureException.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleOptimisticLock(<br>        OptimisticLockingFailureException ex, HttpServletRequest req<br>    ) {<br>        return problem(HttpStatus.CONFLICT, &quot;optimistic-lock-conflict&quot;,<br>            &quot;The resource was modified by another request. Fetch the latest version and retry.&quot;,<br>            req.getRequestURI());<br>    }</pre><pre>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ProblemDetail&gt; handleGeneral(<br>        Exception ex, HttpServletRequest req<br>    ) {<br>        log.error(&quot;Unhandled exception on {} {}&quot;, req.getMethod(), req.getRequestURI(), ex);<br>        // Stack trace&#39;i client&#39;a asla sızdırma<br>        return problem(HttpStatus.INTERNAL_SERVER_ERROR, &quot;internal-error&quot;,<br>            &quot;An unexpected error occurred. Please contact support.&quot;, req.getRequestURI());<br>    }</pre><pre>    private ResponseEntity&lt;ProblemDetail&gt; problem(<br>        HttpStatus status, String type, String detail, String instance<br>    ) {<br>        ProblemDetail body = new ProblemDetail(<br>            BASE_TYPE + type, status.getReasonPhrase(),<br>            status.value(), detail, instance, Instant.now(), Map.of()<br>        );<br>        return ResponseEntity.status(status)<br>            .contentType(MediaType.APPLICATION_PROBLEM_JSON)<br>            .body(body);<br>    }<br>}</pre><p>Response örneği:</p><pre>{<br>  &quot;type&quot;: &quot;https://api.yourdomain.com/errors/validation-error&quot;,<br>  &quot;title&quot;: &quot;Validation Failed&quot;,<br>  &quot;status&quot;: 422,<br>  &quot;detail&quot;: &quot;One or more fields failed validation&quot;,<br>  &quot;instance&quot;: &quot;/api/v1/users&quot;,<br>  &quot;timestamp&quot;: &quot;2025-04-01T10:00:00Z&quot;,<br>  &quot;violations&quot;: [<br>    { &quot;field&quot;: &quot;email&quot;, &quot;message&quot;: &quot;must be a valid email&quot;, &quot;rejectedValue&quot;: &quot;not-an-email&quot; },<br>    { &quot;field&quot;: &quot;age&quot;,   &quot;message&quot;: &quot;must be at least 18&quot;,   &quot;rejectedValue&quot;: 15 }<br>  ]<br>}</pre><p>Content-Type header’ına dikkat: application/problem+json — bu RFC 7807 standardının bir parçasıdır.</p><h3>5. Request Validation — Katmanlı Strateji</h3><p>Validation tek bir yerde değil, birden fazla katmanda yapılmalıdır.</p><pre>HTTP Layer   → Content-Type, boyut limitleri<br>Controller   → @Valid ile Bean Validation (format, boşluk, regex)<br>Service      → İş kuralı validasyonu (çakışmalar, state kontrolü)<br>Database     → Unique constraint, foreign key, not-null</pre><h3>Request DTO — Tam Örnek</h3><pre>public record CreateOrderRequest(</pre><pre>    @NotNull(message = &quot;Customer ID is required&quot;)<br>    UUID customerId,</pre><pre>    @NotEmpty(message = &quot;Order must contain at least one item&quot;)<br>    @Size(max = 50, message = &quot;Order cannot exceed 50 items&quot;)<br>    @Valid<br>    List&lt;OrderItemRequest&gt; items,</pre><pre>    @Valid<br>    ShippingAddressRequest shippingAddress,</pre><pre>    @NotNull<br>    CurrencyCode currency,</pre><pre>    @FutureOrPresent<br>    LocalDate requestedDeliveryDate</pre><pre>) {}</pre><pre>public record OrderItemRequest(</pre><pre>    @NotNull<br>    UUID productId,</pre><pre>    @NotNull @Min(1) @Max(999)<br>    Integer quantity,</pre><pre>    // İsteğe bağlı — sunucu fiyatı belirler; client&#39;tan gelen fiyata güvenilmez<br>    @DecimalMin(&quot;0.01&quot;)<br>    BigDecimal unitPrice</pre><pre>) {}</pre><h3>İş Kuralı Validasyonu — Service Katmanında</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final ProductRepository productRepository;<br>    private final CustomerRepository customerRepository;<br>    private final InventoryService inventoryService;</pre><pre>    @Transactional<br>    public OrderDTO create(CreateOrderRequest request, String idempotencyKey) {</pre><pre>        // İş kuralı: müşteri aktif olmalı<br>        Customer customer = customerRepository.findById(request.customerId())<br>            .filter(Customer::isActive)<br>            .orElseThrow(() -&gt; new BusinessRuleViolationException(<br>                &quot;Customer is not active or does not exist: &quot; + request.customerId()<br>            ));</pre><pre>        // İş kuralı: tüm ürünler stokta mevcut olmalı<br>        request.items().forEach(item -&gt; {<br>            if (!inventoryService.isAvailable(item.productId(), item.quantity())) {<br>                throw new BusinessRuleViolationException(<br>                    &quot;Insufficient stock for product: &quot; + item.productId()<br>                );<br>            }<br>        });</pre><pre>        // ... sipariş oluşturma mantığı<br>    }<br>}</pre><h3>6. Pagination, Cursor-based Sayfalama ve Filtering</h3><h3>Offset vs Cursor Pagination</h3><p><strong>Offset Pagination</strong> (page=2&amp;size=20) basit ama büyük veri setlerinde bozulur:</p><pre>-- page=100, size=20 için veritabanı 2020 satır okur, 2000&#39;ini atar<br>SELECT * FROM orders ORDER BY created_at DESC LIMIT 20 OFFSET 2000;</pre><p>Ayrıca, sayfalama devam ederken yeni kayıt eklenmesi durumunda aynı kaydın iki sayfada görünmesi veya kayıtların atlanması sorunları yaşanır.</p><p><strong>Cursor Pagination</strong> bu sorunları çözer:</p><pre>public record CursorPageRequest(<br>    @Min(1) @Max(100)<br>    int size,<br>    String cursor,          // base64 encoded opaque token<br>    CursorDirection direction<br>) {}</pre><pre>public record CursorPage&lt;T&gt;(<br>    List&lt;T&gt; content,<br>    String nextCursor,<br>    String previousCursor,<br>    boolean hasNext,<br>    boolean hasPrevious<br>) {}</pre><pre>@GetMapping(&quot;/orders&quot;)<br>public ResponseEntity&lt;CursorPage&lt;OrderDTO&gt;&gt; listOrders(<br>    @Valid CursorPageRequest pageRequest,<br>    @Valid OrderFilter filter<br>) {<br>    return ResponseEntity.ok(orderService.findWithCursor(pageRequest, filter));<br>}</pre><pre>// Service implementasyonu<br>public CursorPage&lt;OrderDTO&gt; findWithCursor(CursorPageRequest request, OrderFilter filter) {<br>    Instant cursorTime = request.cursor() != null<br>        ? decodeCursor(request.cursor())<br>        : Instant.now();</pre><pre>    List&lt;Order&gt; orders = orderRepository.findByCursor(<br>        filter, cursorTime, request.direction(), request.size() + 1<br>    );</pre><pre>    boolean hasMore = orders.size() &gt; request.size();<br>    if (hasMore) orders = orders.subList(0, request.size());</pre><pre>    return new CursorPage&lt;&gt;(<br>        orders.stream().map(orderMapper::toDTO).toList(),<br>        hasMore ? encodeCursor(orders.getLast().getCreatedAt()) : null,<br>        request.cursor(),<br>        hasMore,<br>        request.cursor() != null<br>    );<br>}</pre><h3>Specification ile Tip-Güvenli Filtreleme</h3><pre>public class OrderSpecifications {</pre><pre>    public static Specification&lt;Order&gt; hasStatus(OrderStatus status) {<br>        return (root, q, cb) -&gt;<br>            status == null ? null : cb.equal(root.get(&quot;status&quot;), status);<br>    }</pre><pre>    public static Specification&lt;Order&gt; belongsToCustomer(UUID customerId) {<br>        return (root, q, cb) -&gt;<br>            customerId == null ? null : cb.equal(root.get(&quot;customerId&quot;), customerId);<br>    }</pre><pre>    public static Specification&lt;Order&gt; createdBetween(Instant from, Instant to) {<br>        return (root, q, cb) -&gt; {<br>            if (from == null &amp;&amp; to == null) return null;<br>            if (from == null) return cb.lessThanOrEqualTo(root.get(&quot;createdAt&quot;), to);<br>            if (to == null)   return cb.greaterThanOrEqualTo(root.get(&quot;createdAt&quot;), from);<br>            return cb.between(root.get(&quot;createdAt&quot;), from, to);<br>        };<br>    }</pre><pre>    public static Specification&lt;Order&gt; totalBetween(BigDecimal min, BigDecimal max) {<br>        return (root, q, cb) -&gt; {<br>            if (min == null &amp;&amp; max == null) return null;<br>            if (min == null) return cb.le(root.get(&quot;totalAmount&quot;), max);<br>            if (max == null) return cb.ge(root.get(&quot;totalAmount&quot;), min);<br>            return cb.between(root.get(&quot;totalAmount&quot;), min, max);<br>        };<br>    }<br>}</pre><h3>7. DTO Tasarımı, Projeksiyon ve CQRS Ayrımı</h3><h3>Bir Entity İçin Birden Fazla DTO</h3><pre>// Liste görünümü — lightweight<br>public record OrderSummaryDTO(<br>    UUID id,<br>    String status,<br>    BigDecimal totalAmount,<br>    int itemCount,<br>    Instant createdAt<br>) {}</pre><pre>// Detay görünümü — ilişkilerle birlikte<br>public record OrderDetailDTO(<br>    UUID id,<br>    String status,<br>    CustomerSummaryDTO customer,<br>    List&lt;OrderItemDTO&gt; items,<br>    ShippingAddressDTO shippingAddress,<br>    BigDecimal subtotal,<br>    BigDecimal tax,<br>    BigDecimal totalAmount,<br>    Instant createdAt,<br>    Instant updatedAt<br>) {}</pre><pre>// Admin görünümü — iç alanlar dahil<br>public record OrderAdminDTO(<br>    UUID id,<br>    String status,<br>    CustomerSummaryDTO customer,<br>    List&lt;OrderItemDTO&gt; items,<br>    BigDecimal totalAmount,<br>    String internalNotes,<br>    UUID assignedAgentId,<br>    String fraudScore,<br>    Instant createdAt<br>) {}</pre><h3>JPA Projection ile N+1 Kaçınma</h3><pre>// Entity&#39;yi yükleme — JOIN FETCH ile<br>@Query(&quot;&quot;&quot;<br>    SELECT o FROM Order o<br>    JOIN FETCH o.customer<br>    JOIN FETCH o.items i<br>    JOIN FETCH i.product<br>    WHERE o.id = :id<br>    &quot;&quot;&quot;)<br>Optional&lt;Order&gt; findByIdWithDetails(@Param(&quot;id&quot;) UUID id);</pre><pre>// Ya da doğrudan DTO projeksiyon (daha verimli)<br>@Query(&quot;&quot;&quot;<br>    SELECT new com.example.dto.OrderSummaryDTO(<br>        o.id, o.status, o.totalAmount,<br>        SIZE(o.items), o.createdAt<br>    )<br>    FROM Order o<br>    WHERE o.customerId = :customerId<br>    ORDER BY o.createdAt DESC<br>    &quot;&quot;&quot;)<br>Page&lt;OrderSummaryDTO&gt; findSummariesByCustomer(<br>    @Param(&quot;customerId&quot;) UUID customerId, Pageable pageable<br>);</pre><h3>CQRS Yaklaşımı — Okuma ve Yazma Servislerini Ayır</h3><pre>// Command tarafı — transaction yönetimi, domain logic<br>@Service<br>@Transactional<br>public class OrderCommandService {<br>    public OrderDTO create(CreateOrderRequest request) { ... }<br>    public OrderDTO cancel(UUID id, CancelOrderRequest request) { ... }<br>    public OrderDTO updateStatus(UUID id, UpdateStatusRequest request) { ... }<br>}</pre><pre>// Query tarafı — read-only, optimize sorgular<br>@Service<br>@Transactional(readOnly = true)<br>public class OrderQueryService {<br>    public OrderDetailDTO findById(UUID id) { ... }<br>    public CursorPage&lt;OrderSummaryDTO&gt; findAll(OrderFilter filter, CursorPageRequest page) { ... }<br>    public OrderStatisticsDTO getStatistics(UUID customerId, YearMonth period) { ... }<br>}</pre><h3>8. Optimistic Locking ve Concurrency Kontrolü</h3><p>İki kullanıcı aynı kaydı aynı anda güncellemeye çalışırsa ne olur? Optimistic locking bu çakışmayı veritabanı seviyesinde değil uygulama seviyesinde yakalar.</p><h3>Entity’de Version Alanı</h3><pre>@Entity<br>public class Order {</pre><pre>    @Id<br>    private UUID id;</pre><pre>    @Version<br>    private Long version;   // JPA tarafından otomatik yönetilir</pre><pre>    private OrderStatus status;<br>    private BigDecimal totalAmount;<br>    // ...<br>}</pre><h3>Response’a Version Dahil Et</h3><pre>public record OrderDTO(<br>    UUID id,<br>    String status,<br>    BigDecimal totalAmount,<br>    Long version,       // client bu değeri PATCH/PUT isteğinde geri gönderir<br>    Instant updatedAt<br>) {}</pre><h3>Client’tan Gelen Version Kontrolü</h3><pre>@PatchMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;OrderDTO&gt; patch(<br>    @PathVariable UUID id,<br>    @RequestHeader(&quot;If-Match&quot;) String eTag,    // &quot;42&quot; gibi — version numarası<br>    @Valid @RequestBody PatchOrderRequest request<br>) {<br>    Long expectedVersion = parseETag(eTag);<br>    return ResponseEntity.ok(orderService.patch(id, expectedVersion, request));<br>}</pre><pre>@Transactional<br>public OrderDTO patch(UUID id, Long expectedVersion, PatchOrderRequest request) {<br>    Order order = orderRepository.findById(id)<br>        .orElseThrow(() -&gt; new ResourceNotFoundException(&quot;Order not found: &quot; + id));</pre><pre>    if (!order.getVersion().equals(expectedVersion)) {<br>        throw new OptimisticLockingFailureException(<br>            &quot;Order was modified by another request. Current version: &quot; + order.getVersion()<br>        );<br>    }</pre><pre>    // ... güncelleme<br>    return orderMapper.toDTO(orderRepository.save(order));<br>}</pre><p>Conflict durumunda client 409 Conflict alır ve son versiyonu çekip tekrar denemesi gerektiğini anlar.</p><h3>9. Idempotency Keys — POST İsteklerini Güvenli Yapmak</h3><p>Ağ kesintileri gerçek hayatta olur. Sipariş oluşturma veya ödeme gibi kritik POST işlemleri, güvenli biçimde yeniden denenebilir olmalıdır.</p><pre>Client → POST /orders [Idempotency-Key: uuid-abc] → Server (başarılı, 201)<br>Client → Yanıt alınamadı (timeout)<br>Client → POST /orders [Idempotency-Key: uuid-abc] → Server (aynı key, 201 + cached response)</pre><h3>Implementasyon</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class IdempotencyService {</pre><pre>    private final IdempotencyKeyRepository repository;<br>    private final ObjectMapper objectMapper;</pre><pre>    public &lt;T&gt; Optional&lt;ResponseEntity&lt;T&gt;&gt; findCachedResponse(String key, Class&lt;T&gt; type) {<br>        return repository.findByKey(key)<br>            .map(record -&gt; {<br>                T body = objectMapper.convertValue(record.responseBody(), type);<br>                return ResponseEntity<br>                    .status(record.httpStatus())<br>                    .body(body);<br>            });<br>    }</pre><pre>    public void store(String key, int status, Object responseBody) {<br>        repository.save(new IdempotencyRecord(<br>            key, status, responseBody, Instant.now().plusSeconds(86400) // 24 saat TTL<br>        ));<br>    }<br>}</pre><pre>@PostMapping(&quot;/orders&quot;)<br>public ResponseEntity&lt;OrderDTO&gt; create(<br>    @Valid @RequestBody CreateOrderRequest request,<br>    @RequestHeader(value = &quot;Idempotency-Key&quot;, required = false) String idempotencyKey<br>) {<br>    if (idempotencyKey != null) {<br>        Optional&lt;ResponseEntity&lt;OrderDTO&gt;&gt; cached =<br>            idempotencyService.findCachedResponse(idempotencyKey, OrderDTO.class);<br>        if (cached.isPresent()) return cached.get();<br>    }</pre><pre>    OrderDTO order = orderService.create(request);<br>    ResponseEntity&lt;OrderDTO&gt; response = ResponseEntity<br>        .created(URI.create(&quot;/api/v1/orders/&quot; + order.id()))<br>        .body(order);</pre><pre>    if (idempotencyKey != null) {<br>        idempotencyService.store(idempotencyKey, 201, order);<br>    }</pre><pre>    return response;<br>}</pre><h3>10. Conditional Requests — ETag ve If-Modified-Since</h3><p>ETag’ler gereksiz veri transferini önler, bant genişliğini azaltır ve cache tutarlılığını sağlar.</p><h3>ETag Üretimi</h3><pre>@GetMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;OrderDTO&gt; get(<br>    @PathVariable UUID id,<br>    @RequestHeader(value = &quot;If-None-Match&quot;, required = false) String ifNoneMatch<br>) {<br>    OrderDTO order = orderService.findById(id);<br>    String etag = generateETag(order);</pre><pre>    if (etag.equals(ifNoneMatch)) {<br>        return ResponseEntity.status(HttpStatus.NOT_MODIFIED).build(); // 304 — veri yok<br>    }</pre><pre>    return ResponseEntity.ok()<br>        .eTag(etag)<br>        .lastModified(order.updatedAt())<br>        .body(order);<br>}</pre><pre>private String generateETag(OrderDTO order) {<br>    // Version numarası veya içerik hash&#39;i kullan<br>    return &quot;\&quot;&quot; + order.version() + &quot;\&quot;&quot;;<br>}</pre><p>Client ikinci istekte If-None-Match: &quot;42&quot; header&#39;ını gönderir. Kaynak değişmemişse sunucu 304 Not Modified döner ve body transfer edilmez.</p><h3>Shallow ETag Filter (Spring’de Hazır)</h3><pre>@Bean<br>public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {<br>    return new ShallowEtagHeaderFilter();<br>}</pre><p>Bu filter response body’nin MD5 hash’ini otomatik hesaplar ve ETag header’ı olarak ekler.</p><h3>11. API Versiyonlama — Strateji ve Deprecation</h3><h3>Hangi Strateji?</h3><p>Strateji Örnek Avantaj Dezavantaj URI /api/v2/users Açık, cache dostu URL&#39;i &quot;kirletiyor&quot; Header X-API-Version: 2 Temiz URL Cache zorluğu, keşfedilebilirlik düşük Media Type Accept: application/vnd.api.v2+json REST-pure Karmaşık, az destek</p><p><strong>Recommendation:</strong> URI versiyonlama en pragmatik tercihtir — tooling desteği en güçlü, debug en kolayı.</p><h3>Breaking vs Non-Breaking Change</h3><pre>Non-breaking (versiyonsuz yapılabilir):<br>  + Yeni endpoint ekleme<br>  + Mevcut response&#39;a opsiyonel alan ekleme<br>  + Yeni query parametresi ekleme (opsiyonel)</pre><pre>Breaking (yeni versiyon gerektirir):<br>  - Alan kaldırma veya yeniden adlandırma<br>  - Alan tipini değiştirme<br>  - Zorunlu alan ekleme<br>  - Status code değiştirme<br>  - URL yapısını değiştirme</pre><h3>Deprecation Lifecycle</h3><pre>@GetMapping(&quot;/users/{id}&quot;)<br>public ResponseEntity&lt;UserV1DTO&gt; getUserV1(@PathVariable UUID id) {<br>    UserV1DTO user = userService.findByIdV1(id);<br>    return ResponseEntity.ok()<br>        .header(&quot;Deprecation&quot;, &quot;true&quot;)<br>        .header(&quot;Sunset&quot;, &quot;Mon, 01 Sep 2025 00:00:00 GMT&quot;)   // RFC 7231 tarih formatı<br>        .header(&quot;Link&quot;, &quot;&lt;/api/v2/users/&quot; + id + &quot;&gt;; rel=\&quot;successor-version\&quot;&quot;)<br>        .header(&quot;Warning&quot;, &quot;299 - \&quot;This endpoint is deprecated. Use /api/v2/users\&quot;&quot;)<br>        .body(user);<br>}</pre><h3>12. Authentication, Authorization ve Fine-Grained Erişim</h3><h3>JWT Token Yapısı</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class JwtService {</pre><pre>    @Value(&quot;${jwt.secret}&quot;)<br>    private String secret;</pre><pre>    @Value(&quot;${jwt.expiration:3600}&quot;)<br>    private long expirationSeconds;</pre><pre>    public String generateToken(User user) {<br>        return Jwts.builder()<br>            .subject(user.getId().toString())<br>            .claim(&quot;email&quot;, user.getEmail())<br>            .claim(&quot;roles&quot;, user.getRoles())<br>            .claim(&quot;permissions&quot;, user.getPermissions())  // fine-grained<br>            .issuedAt(new Date())<br>            .expiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))<br>            .signWith(getSigningKey(), SignatureAlgorithm.HS256)<br>            .compact();<br>    }<br>}</pre><h3>Resource-Level Ownership Kontrolü</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderAuthorizationService {</pre><pre>    public void assertCanRead(UUID orderId, SecurityContext ctx) {<br>        User user = (User) ctx.getAuthentication().getPrincipal();<br>        if (user.hasRole(&quot;ADMIN&quot;)) return;  // admin her şeyi görebilir</pre><pre>        Order order = orderRepository.findById(orderId)<br>            .orElseThrow(() -&gt; new ResourceNotFoundException(&quot;Order not found: &quot; + orderId));</pre><pre>        if (!order.getCustomerId().equals(user.getId())) {<br>            throw new AccessDeniedException(&quot;You don&#39;t have access to this order&quot;);<br>        }<br>    }</pre><pre>    public void assertCanModify(UUID orderId, SecurityContext ctx) {<br>        assertCanRead(orderId, ctx);<br>        Order order = orderRepository.findById(orderId).orElseThrow();<br>        if (order.getStatus() != OrderStatus.PENDING) {<br>            throw new BusinessRuleViolationException(<br>                &quot;Only PENDING orders can be modified. Current status: &quot; + order.getStatus()<br>            );<br>        }<br>    }<br>}</pre><h3>Spring Security Method Security</h3><pre>@Configuration<br>@EnableMethodSecurity<br>public class SecurityConfig { ... }</pre><pre>@RestController<br>public class OrderController {</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;) or @orderAuthorizationService.canRead(#id, authentication)&quot;)<br>    public ResponseEntity&lt;OrderDetailDTO&gt; get(@PathVariable UUID id) { ... }</pre><pre>    @DeleteMapping(&quot;/{id}&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>    public ResponseEntity&lt;Void&gt; delete(@PathVariable UUID id) { ... }<br>}</pre><h3>13. CORS ve Güvenlik Header’ları</h3><h3>CORS — Ortam Bazlı Konfigürasyon</h3><pre>@Configuration<br>public class SecurityHeadersConfig implements WebMvcConfigurer {</pre><pre>    @Value(&quot;${app.cors.allowed-origins}&quot;)<br>    private List&lt;String&gt; allowedOrigins;</pre><pre>    @Override<br>    public void addCorsMappings(CorsRegistry registry) {<br>        registry.addMapping(&quot;/api/**&quot;)<br>            .allowedOrigins(allowedOrigins.toArray(String[]::new))<br>            .allowedMethods(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;)<br>            .allowedHeaders(&quot;Authorization&quot;, &quot;Content-Type&quot;, &quot;Idempotency-Key&quot;,<br>                           &quot;If-Match&quot;, &quot;If-None-Match&quot;)<br>            .exposedHeaders(&quot;ETag&quot;, &quot;Location&quot;, &quot;X-Trace-Id&quot;,<br>                           &quot;X-Rate-Limit-Remaining&quot;, &quot;Retry-After&quot;)<br>            .allowCredentials(true)<br>            .maxAge(3600);<br>    }<br>}</pre><h3>Güvenlik Header’ları</h3><pre>@Component<br>public class SecurityHeadersFilter extends OncePerRequestFilter {</pre><pre>    @Override<br>    protected void doFilterInternal(<br>        HttpServletRequest req, HttpServletResponse res, FilterChain chain<br>    ) throws ServletException, IOException {</pre><pre>        // Clickjacking koruması<br>        res.setHeader(&quot;X-Frame-Options&quot;, &quot;DENY&quot;);<br>        // MIME sniffing koruması<br>        res.setHeader(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;);<br>        // XSS koruması<br>        res.setHeader(&quot;X-XSS-Protection&quot;, &quot;1; mode=block&quot;);<br>        // Referrer politikası<br>        res.setHeader(&quot;Referrer-Policy&quot;, &quot;strict-origin-when-cross-origin&quot;);<br>        // Content Security Policy<br>        res.setHeader(&quot;Content-Security-Policy&quot;, &quot;default-src &#39;self&#39;&quot;);<br>        // HSTS — HTTPS zorunlu<br>        res.setHeader(&quot;Strict-Transport-Security&quot;, &quot;max-age=31536000; includeSubDomains&quot;);</pre><pre>        chain.doFilter(req, res);<br>    }<br>}</pre><h3>14. Rate Limiting ve Throttling Stratejileri</h3><h3>Farklı Limitleme Stratejileri</h3><pre>public enum RateLimitStrategy {<br>    PER_IP,          // Genel koruma<br>    PER_USER,        // Authenticated kullanıcılar<br>    PER_API_KEY,     // B2B entegrasyonlar<br>    PER_ENDPOINT     // Özellikle hassas endpoint&#39;ler<br>}</pre><h3>Sliding Window Rate Limiter (Redis ile)</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class RedisRateLimiter {</pre><pre>    private final RedisTemplate&lt;String, String&gt; redisTemplate;</pre><pre>    public RateLimitResult tryConsume(String key, int limit, Duration window) {<br>        String redisKey = &quot;rate_limit:&quot; + key;<br>        long now = Instant.now().toEpochMilli();<br>        long windowStart = now - window.toMillis();</pre><pre>        // Sliding window — eski kayıtları temizle<br>        redisTemplate.opsForZSet().removeRangeByScore(redisKey, 0, windowStart);</pre><pre>        Long count = redisTemplate.opsForZSet().zCard(redisKey);<br>        long remaining = Math.max(0, limit - (count == null ? 0 : count));</pre><pre>        if (remaining &lt;= 0) {<br>            // En eski kaydın zamanı — ne zaman yeniden denenebileceği<br>            Set&lt;ZSetOperations.TypedTuple&lt;String&gt;&gt; oldest =<br>                redisTemplate.opsForZSet().rangeWithScores(redisKey, 0, 0);<br>            long retryAfterMs = oldest.isEmpty() ? window.toMillis()<br>                : (long)(oldest.iterator().next().getScore()) + window.toMillis() - now;</pre><pre>            return RateLimitResult.exceeded(Duration.ofMillis(retryAfterMs));<br>        }</pre><pre>        redisTemplate.opsForZSet().add(redisKey, UUID.randomUUID().toString(), now);<br>        redisTemplate.expire(redisKey, window);</pre><pre>        return RateLimitResult.allowed(remaining);<br>    }<br>}</pre><pre>@Component<br>@RequiredArgsConstructor<br>public class RateLimitingFilter extends OncePerRequestFilter {</pre><pre>    private final RedisRateLimiter rateLimiter;<br>    private final AuthenticationService authService;</pre><pre>    @Override<br>    protected void doFilterInternal(<br>        HttpServletRequest req, HttpServletResponse res, FilterChain chain<br>    ) throws ServletException, IOException {</pre><pre>        String key = resolveKey(req);<br>        RateLimitResult result = rateLimiter.tryConsume(key, 100, Duration.ofMinutes(1));</pre><pre>        res.addHeader(&quot;X-Rate-Limit-Limit&quot;, &quot;100&quot;);<br>        res.addHeader(&quot;X-Rate-Limit-Remaining&quot;, String.valueOf(result.remaining()));</pre><pre>        if (result.isExceeded()) {<br>            res.addHeader(&quot;Retry-After&quot;,<br>                String.valueOf(result.retryAfter().getSeconds()));<br>            res.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());<br>            res.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);<br>            res.getWriter().write(&quot;&quot;&quot;<br>                {<br>                  &quot;type&quot;: &quot;https://api.yourdomain.com/errors/rate-limit-exceeded&quot;,<br>                  &quot;title&quot;: &quot;Too Many Requests&quot;,<br>                  &quot;status&quot;: 429,<br>                  &quot;detail&quot;: &quot;Rate limit exceeded. Retry after %d seconds.&quot;<br>                }<br>                &quot;&quot;&quot;.formatted(result.retryAfter().getSeconds()));<br>            return;<br>        }</pre><pre>        chain.doFilter(req, res);<br>    }</pre><pre>    private String resolveKey(HttpServletRequest req) {<br>        // Authenticated kullanıcı varsa user ID, yoksa IP<br>        return authService.getCurrentUserId()<br>            .map(id -&gt; &quot;user:&quot; + id)<br>            .orElse(&quot;ip:&quot; + req.getRemoteAddr());<br>    }<br>}</pre><h3>15. N+1 Sorunu ve Veritabanı Optimizasyonu</h3><h3>N+1 Sorununu Tespit Et</h3><pre>// spring.jpa.show-sql=true ile görülen tehlikeli pattern:<br>// SELECT * FROM orders WHERE ...        ← 1 sorgu<br>// SELECT * FROM order_items WHERE id=1  ← N sorgu (her sipariş için)<br>// SELECT * FROM order_items WHERE id=2<br>// SELECT * FROM order_items WHERE id=3<br>// ...</pre><h3>Çözüm 1 — JOIN FETCH</h3><pre>@Query(&quot;&quot;&quot;<br>    SELECT DISTINCT o FROM Order o<br>    LEFT JOIN FETCH o.items i<br>    LEFT JOIN FETCH i.product<br>    WHERE o.customerId = :customerId<br>    &quot;&quot;&quot;)<br>List&lt;Order&gt; findAllWithItemsByCustomer(@Param(&quot;customerId&quot;) UUID customerId);</pre><h3>Çözüm 2 — @EntityGraph</h3><pre>@EntityGraph(attributePaths = {&quot;items&quot;, &quot;items.product&quot;, &quot;customer&quot;})<br>@Query(&quot;SELECT o FROM Order o WHERE o.id = :id&quot;)<br>Optional&lt;Order&gt; findByIdWithGraph(@Param(&quot;id&quot;) UUID id);</pre><h3>Çözüm 3 — Batch Size (N+1 etkisini azaltır)</h3><pre>@Entity<br>public class Order {<br>    @OneToMany(mappedBy = &quot;order&quot;)<br>    @BatchSize(size = 30)  // Hibernate 30&#39;ar 30&#39;ar yükler, N+1 yerine N/30+1 sorgu<br>    private List&lt;OrderItem&gt; items;<br>}</pre><h3>Çözüm 4 — Sadece İhtiyaç Duyulan Alanları Çek (Interface Projection)</h3><pre>public interface OrderSummaryProjection {<br>    UUID getId();<br>    String getStatus();<br>    BigDecimal getTotalAmount();<br>    Instant getCreatedAt();<br>}</pre><pre>List&lt;OrderSummaryProjection&gt; findByCustomerId(UUID customerId, Pageable pageable);</pre><p>Bu yaklaşım entity’yi tamamen yüklemeden yalnızca gerekli sütunları çeker.</p><h3>16. Observability — Logging, Metrics ve Distributed Tracing</h3><h3>Structured Logging ile MDC</h3><pre>@Component<br>@Slf4j<br>public class ObservabilityFilter extends OncePerRequestFilter {</pre><pre>    @Override<br>    protected void doFilterInternal(<br>        HttpServletRequest req, HttpServletResponse res, FilterChain chain<br>    ) throws ServletException, IOException {</pre><pre>        String traceId = Optional.ofNullable(req.getHeader(&quot;X-Trace-Id&quot;))<br>            .orElse(UUID.randomUUID().toString());<br>        String spanId = UUID.randomUUID().toString().substring(0, 8);</pre><pre>        MDC.put(&quot;traceId&quot;,   traceId);<br>        MDC.put(&quot;spanId&quot;,    spanId);<br>        MDC.put(&quot;method&quot;,    req.getMethod());<br>        MDC.put(&quot;path&quot;,      req.getRequestURI());<br>        MDC.put(&quot;userAgent&quot;, req.getHeader(&quot;User-Agent&quot;));</pre><pre>        res.setHeader(&quot;X-Trace-Id&quot;, traceId);<br>        res.setHeader(&quot;X-Span-Id&quot;,  spanId);</pre><pre>        long start = System.currentTimeMillis();<br>        try {<br>            chain.doFilter(req, res);<br>        } finally {<br>            long duration = System.currentTimeMillis() - start;<br>            MDC.put(&quot;status&quot;,   String.valueOf(res.getStatus()));<br>            MDC.put(&quot;duration&quot;, duration + &quot;ms&quot;);<br>            log.info(&quot;HTTP {} {} → {} ({}ms)&quot;,<br>                req.getMethod(), req.getRequestURI(), res.getStatus(), duration);<br>            MDC.clear();<br>        }<br>    }<br>}</pre><h3>Micrometer ile Custom Metrics</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {</pre><pre>    private final MeterRegistry meterRegistry;</pre><pre>    public OrderDTO create(CreateOrderRequest request) {<br>        return Timer.builder(&quot;order.creation.duration&quot;)<br>            .tag(&quot;currency&quot;, request.currency().toString())<br>            .register(meterRegistry)<br>            .record(() -&gt; {<br>                OrderDTO order = doCreate(request);<br>                meterRegistry.counter(&quot;orders.created&quot;,<br>                    &quot;status&quot;, &quot;success&quot;,<br>                    &quot;currency&quot;, request.currency().toString()<br>                ).increment();<br>                return order;<br>            });<br>    }<br>}</pre><h3>Spring Boot Actuator + Prometheus</h3><pre>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: health, info, metrics, prometheus<br>  endpoint:<br>    health:<br>      show-details: when-authorized<br>  metrics:<br>    export:<br>      prometheus:<br>        enabled: true</pre><pre>@Component<br>public class CustomHealthIndicator implements HealthIndicator {</pre><pre>    private final ExternalPaymentService paymentService;</pre><pre>    @Override<br>    public Health health() {<br>        try {<br>            paymentService.ping();<br>            return Health.up()<br>                .withDetail(&quot;payment-gateway&quot;, &quot;reachable&quot;)<br>                .build();<br>        } catch (Exception e) {<br>            return Health.down()<br>                .withDetail(&quot;payment-gateway&quot;, &quot;unreachable&quot;)<br>                .withException(e)<br>                .build();<br>        }<br>    }<br>}</pre><h3>17. OpenAPI ve Sözleşme Öncelikli Geliştirme</h3><h3>Code-First (Annotation ile)</h3><pre>@Tag(name = &quot;Orders&quot;, description = &quot;Order management operations&quot;)<br>@RestController<br>@RequestMapping(&quot;/api/v1/orders&quot;)<br>public class OrderController {</pre><pre>    @Operation(<br>        summary = &quot;Create a new order&quot;,<br>        description = &quot;Creates a new order. Supports idempotent creation via Idempotency-Key header.&quot;<br>    )<br>    @ApiResponses({<br>        @ApiResponse(responseCode = &quot;201&quot;, description = &quot;Order created successfully&quot;,<br>            headers = @Header(name = &quot;Location&quot;, description = &quot;URL of the created order&quot;)),<br>        @ApiResponse(responseCode = &quot;400&quot;, description = &quot;Invalid request&quot;,<br>            content = @Content(<br>                mediaType = &quot;application/problem+json&quot;,<br>                schema = @Schema(implementation = ProblemDetail.class))),<br>        @ApiResponse(responseCode = &quot;409&quot;, description = &quot;Duplicate idempotency key with different payload&quot;,<br>            content = @Content(mediaType = &quot;application/problem+json&quot;))<br>    })<br>    @PostMapping<br>    public ResponseEntity&lt;OrderDTO&gt; create(<br>        @Parameter(description = &quot;Unique key for idempotent request processing&quot;)<br>        @RequestHeader(value = &quot;Idempotency-Key&quot;, required = false) String idempotencyKey,<br>        @Valid @RequestBody CreateOrderRequest request<br>    ) { ... }<br>}</pre><h3>Schema Annotation’ları</h3><pre>@Schema(description = &quot;Request payload for creating a new order&quot;)<br>public record CreateOrderRequest(</pre><pre>    @Schema(description = &quot;Customer UUID&quot;, example = &quot;550e8400-e29b-41d4-a716-446655440000&quot;)<br>    @NotNull UUID customerId,</pre><pre>    @Schema(description = &quot;Order line items, minimum 1 required&quot;)<br>    @NotEmpty @Valid List&lt;OrderItemRequest&gt; items,</pre><pre>    @Schema(description = &quot;ISO 4217 currency code&quot;, example = &quot;USD&quot;, allowableValues = {&quot;USD&quot;, &quot;EUR&quot;, &quot;TRY&quot;})<br>    @NotNull CurrencyCode currency</pre><pre>) {}</pre><h3>18. React Tarafında Gelişmiş API Katmanı</h3><h3>Axios Instance — Tam Uygulama</h3><pre>// src/lib/apiClient.js<br>import axios from &#39;axios&#39;;<br>import { authStore } from &#39;@/stores/authStore&#39;;</pre><pre>let isRefreshing = false;<br>let failedQueue = [];</pre><pre>const processQueue = (error, token = null) =&gt; {<br>  failedQueue.forEach(p =&gt; error ? p.reject(error) : p.resolve(token));<br>  failedQueue = [];<br>};</pre><pre>const apiClient = axios.create({<br>  baseURL: import.meta.env.VITE_API_BASE_URL,<br>  timeout: 15_000,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>});</pre><pre>apiClient.interceptors.request.use(config =&gt; {<br>  const token = authStore.getAccessToken();<br>  if (token) config.headers.Authorization = `Bearer ${token}`;</pre><pre>  // Idempotency key — mutating metodlar için<br>  if ([&#39;post&#39;, &#39;put&#39;, &#39;patch&#39;].includes(config.method)) {<br>    config.headers[&#39;Idempotency-Key&#39;] ??= crypto.randomUUID();<br>  }</pre><pre>  return config;<br>});</pre><pre>apiClient.interceptors.response.use(<br>  response =&gt; response,<br>  async error =&gt; {<br>    const originalRequest = error.config;</pre><pre>    if (error.response?.status === 401 &amp;&amp; !originalRequest._retry) {<br>      if (isRefreshing) {<br>        // Token yenileme devam ediyorsa sıraya gir<br>        return new Promise((resolve, reject) =&gt; {<br>          failedQueue.push({ resolve, reject });<br>        }).then(token =&gt; {<br>          originalRequest.headers.Authorization = `Bearer ${token}`;<br>          return apiClient(originalRequest);<br>        });<br>      }</pre><pre>      originalRequest._retry = true;<br>      isRefreshing = true;</pre><pre>      try {<br>        const newToken = await authStore.refreshToken();<br>        processQueue(null, newToken);<br>        originalRequest.headers.Authorization = `Bearer ${newToken}`;<br>        return apiClient(originalRequest);<br>      } catch (refreshError) {<br>        processQueue(refreshError, null);<br>        authStore.logout();<br>        return Promise.reject(refreshError);<br>      } finally {<br>        isRefreshing = false;<br>      }<br>    }</pre><pre>    return Promise.reject(error);<br>  }<br>);</pre><pre>export default apiClient;</pre><h3>React Query — Optimistic Updates</h3><pre>// src/hooks/useOrders.js<br>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br>import { orderService } from &#39;@/services/orderService&#39;;</pre><pre>export const useCancelOrder = () =&gt; {<br>  const queryClient = useQueryClient();</pre><pre>  return useMutation({<br>    mutationFn: ({ id }) =&gt; orderService.cancel(id),</pre><pre>    // 1. İsteği göndermeden önce UI&#39;ı güncelle<br>    onMutate: async ({ id }) =&gt; {<br>      await queryClient.cancelQueries({ queryKey: [&#39;orders&#39;, id] });<br>      const previousOrder = queryClient.getQueryData([&#39;orders&#39;, id]);</pre><pre>      queryClient.setQueryData([&#39;orders&#39;, id], old =&gt; ({<br>        ...old,<br>        status: &#39;CANCELLED&#39;,<br>      }));</pre><pre>      return { previousOrder };<br>    },</pre><pre>    // 2. Hata olursa geri al<br>    onError: (error, { id }, context) =&gt; {<br>      queryClient.setQueryData([&#39;orders&#39;, id], context.previousOrder);<br>    },</pre><pre>    // 3. Başarı veya hata sonrası gerçek veriyi çek<br>    onSettled: (data, error, { id }) =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&#39;orders&#39;, id] });<br>      queryClient.invalidateQueries({ queryKey: [&#39;orders&#39;] });<br>    },<br>  });<br>};</pre><h3>ETag ile Conditional Fetch</h3><pre>// src/services/orderService.js<br>const etagCache = new Map();</pre><pre>export const orderService = {<br>  getById: async (id) =&gt; {<br>    const cachedEtag = etagCache.get(`order:${id}`);<br>    const headers = cachedEtag ? { &#39;If-None-Match&#39;: cachedEtag } : {};</pre><pre>    try {<br>      const response = await apiClient.get(`/orders/${id}`, { headers });<br>      const newEtag = response.headers[&#39;etag&#39;];<br>      if (newEtag) etagCache.set(`order:${id}`, newEtag);<br>      return response.data;<br>    } catch (error) {<br>      if (error.response?.status === 304) {<br>        // Değişmemiş — query cache&#39;den sun<br>        return null; // React Query mevcut veriyi korur<br>      }<br>      throw error;<br>    }<br>  },<br>};</pre><h3>Error Boundary ile API Hataları</h3><pre>// src/components/ApiErrorBoundary.jsx<br>import { useRouteError } from &#39;react-router-dom&#39;;</pre><pre>export function ApiErrorBoundary() {<br>  const error = useRouteError();<br>  const problem = error?.response?.data;</pre><pre>  if (problem?.status === 404) {<br>    return &lt;NotFoundPage /&gt;;<br>  }</pre><pre>  if (problem?.status === 403) {<br>    return &lt;ForbiddenPage /&gt;;<br>  }</pre><pre>  return (<br>    &lt;ErrorPage<br>      title={problem?.title ?? &#39;An error occurred&#39;}<br>      detail={problem?.detail}<br>      traceId={error?.response?.headers?.[&#39;x-trace-id&#39;]}<br>    /&gt;<br>  );<br>}</pre><h3>19. Üretim Ortamı Kontrol Listesi</h3><h3>API Tasarımı ve Sözleşme</h3><ul><li>[ ] HTTP metodları semantik ve idempotency açısından doğru</li><li>[ ] URL’ler tutarlı, noun-based, hiyerarşik</li><li>[ ] RFC 7807 Problem Details uygulandı (application/problem+json)</li><li>[ ] Tüm endpoint’ler aynı hata yapısını kullanıyor</li><li>[ ] ETag ve conditional request desteği kritik endpoint’lerde mevcut</li><li>[ ] Idempotency key desteği POST endpoint’lerinde uygulandı</li><li>[ ] API versiyonlama stratejisi belirlendi, deprecation header’ları aktif</li></ul><h3>Veri ve Performans</h3><ul><li>[ ] Tüm list endpoint’leri sayfalanmış (cursor veya offset)</li><li>[ ] N+1 sorguları test edildi ve giderildi</li><li>[ ] DTO katmanı uygulandı, entity’ler asla doğrudan dönmüyor</li><li>[ ] Optimistic locking kritik kaynaklarda uygulandı</li><li>[ ] Read-only transaction’lar query servislerinde kullanılıyor</li></ul><h3>Güvenlik</h3><ul><li>[ ] JWT doğru yapılandırıldı (kısa TTL, refresh token rotasyonu)</li><li>[ ] Resource-level ownership kontrolü yapılıyor</li><li>[ ] CORS ortama özgü, wildcard yok</li><li>[ ] Güvenlik header’ları (HSTS, CSP, X-Frame-Options) aktif</li><li>[ ] Rate limiting uygulandı, Redis ile distributed ortamda çalışıyor</li><li>[ ] Sensitive field’lar response’a asla dahil edilmiyor</li><li>[ ] HTTPS zorunlu, HTTP otomatik yönlendiriliyor</li></ul><h3>Observability</h3><ul><li>[ ] Her istek için traceId üretiliyor ve response header’ına ekleniyor</li><li>[ ] Structured logging yapılandırıldı (JSON format önerilir)</li><li>[ ] Micrometer + Prometheus metrics aktif</li><li>[ ] Custom health indicator’lar dış bağımlılıkları izliyor</li><li>[ ] OpenAPI dokümantasyonu kod ile senkron tutuluyor</li><li>[ ] Alerting kritik metrikler (error rate, latency, saturation) için kurulu</li></ul><p><em>Referanslar: </em><a href="https://datatracker.ietf.org/doc/html/rfc7807"><em>RFC 7807 — Problem Details</em></a><em> · </em><a href="https://datatracker.ietf.org/doc/html/rfc7232"><em>RFC 7232 — Conditional Requests</em></a><em> · </em><a href="https://datatracker.ietf.org/doc/html/rfc7231"><em>RFC 7231 — HTTP Semantics</em></a><em> · </em><a href="https://cloud.google.com/apis/design"><em>Google API Design Guide</em></a><em> · </em><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/"><em>Spring Boot Docs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c956993714ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding the “God Object” Antipattern in React: Compound Components]]></title>
            <link>https://medium.com/@sahin.ilyd/avoiding-the-god-object-antipattern-in-react-compound-components-8dd3d8f5655c?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd3d8f5655c</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 07:55:12 GMT</pubDate>
            <atom:updated>2026-03-31T07:55:12.263Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Speed is everything in full-stack development, but haste often leads us straight into “Prop Hell” — the chaotic intersection of Prop Drilling and Prop Bloat. Today, we’ll dive into one of the most powerful tools in a Senior React Developer’s arsenal: the Compound Component Pattern.</strong></p><h3>The Problem: “Monolithic” Components That Kill Flexibility</h3><p>The most common mistake is designing a single component to handle every possible use case by cramming in dozens of boolean props (e.g., hasIcon, isSmall, darkTheme). The result? A 500-line unreadable file and logic that breaks with every new feature request.</p><h3>The Solution: Declarative and Shared State</h3><p>The Compound Component pattern keeps the logic within a parent container while delegating the visual presentation to its children. Communication between them is handled “under the hood” via the <strong>Context API</strong>. Think of it like the HTML &lt;select&gt; and &lt;option&gt; relationship.</p><h3>Professional Implementation: An Advanced Stepper</h3><p>Let’s build a structure that isn’t just functional, but safe and performance-optimized.</p><p>TypeScript</p><pre>import React, { <br>  useState, <br>  createContext, <br>  useContext, <br>  useMemo, <br>  useCallback, <br>  ReactNode <br>} from &#39;react&#39;;</pre><pre>// --- TYPING ---<br>interface StepperContextProps {<br>  activeStep: number;<br>  goTo: (step: number) =&gt; void;<br>  next: () =&gt; void;<br>}</pre><pre>const StepperContext = createContext&lt;StepperContextProps | undefined&gt;(undefined);</pre><pre>// --- CUSTOM HOOK (For Error Handling) ---<br>function useStepper() {<br>  const context = useContext(StepperContext);<br>  if (!context) {<br>    throw new Error(&#39;Stepper components cannot be rendered outside of &lt;Stepper /&gt;!&#39;);<br>  }<br>  return context;<br>}</pre><pre>// --- MAIN WRAPPER ---<br>export function Stepper({ children, initialStep = 0 }: { children: ReactNode; initialStep?: number }) {<br>  const [activeStep, setActiveStep] = useState(initialStep);</pre><pre>  const goTo = useCallback((step: number) =&gt; setActiveStep(step), []);<br>  const next = useCallback(() =&gt; setActiveStep(prev =&gt; prev + 1), []);</pre><pre>  // Performance Optimization: Memoizing the context value <br>  // to prevent unnecessary re-renders of the consumer tree.<br>  const value = useMemo(() =&gt; ({ activeStep, goTo, next }), [activeStep, goTo, next]);</pre><pre>  return (<br>    &lt;StepperContext.Provider value={value}&gt;<br>      &lt;div className=&quot;stepper-container border rounded-lg p-4 shadow-sm&quot;&gt;<br>        {children}<br>      &lt;/div&gt;<br>    &lt;/StepperContext.Provider&gt;<br>  );<br>}</pre><pre>// --- SUB-COMPONENTS (Namespace Pattern) ---</pre><pre>const Trigger = ({ index, children }: { index: number; children: ReactNode }) =&gt; {<br>  const { activeStep, goTo } = useStepper();<br>  const isActive = activeStep === index;</pre><pre>  return (<br>    &lt;button<br>      onClick={() =&gt; goTo(index)}<br>      className={`px-4 py-2 rounded transition ${<br>        isActive ? &#39;bg-indigo-600 text-white&#39; : &#39;bg-gray-100&#39;<br>      }`}<br>    &gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>};</pre><pre>const Content = ({ index, children }: { index: number; children: ReactNode }) =&gt; {<br>  const { activeStep } = useStepper();<br>  return activeStep === index ? &lt;div className=&quot;mt-4 py-2&quot;&gt;{children}&lt;/div&gt; : null;<br>};</pre><pre>// Attaching sub-components to the main component for clean imports<br>Stepper.Trigger = Trigger;<br>Stepper.Content = Content;</pre><h3>Why Is This a “Senior” Approach?</h3><ul><li><strong>Inversion of Control (IoC):</strong> We hand the layout control back to the consumer. Want the Trigger at the bottom? Inside a specific div? Surrounded by extra text? You can do it without touching the core logic.</li><li><strong>Memoization:</strong> Using useMemo and useCallback ensures that large-scale applications maintain a low render cost by keeping reference stability.</li><li><strong>Strict Context Check:</strong> By using a custom hook that throws an error, we prevent illegal usage of sub-components outside the provider. This is proactive programming that prevents runtime bugs.</li></ul><h3>Real-World Usage</h3><p>With this structure, you can inject any <strong>Tailwind</strong> classes or additional HTML tags without worrying about prop conflicts:</p><p>TypeScript</p><pre>function SignupForm() {<br>  return (<br>    &lt;Stepper initialStep={0}&gt;<br>      {/* Complete control over the layout */}<br>      &lt;div className=&quot;flex gap-4 border-b pb-2&quot;&gt;<br>        &lt;Stepper.Trigger index={0}&gt;Step 1: Account&lt;/Stepper.Trigger&gt;<br>        &lt;Stepper.Trigger index={1}&gt;Step 2: Security&lt;/Stepper.Trigger&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div className=&quot;content-wrapper bg-slate-50 p-4 rounded&quot;&gt;<br>        &lt;Stepper.Content index={0}&gt;<br>          &lt;h3 className=&quot;font-bold&quot;&gt;Create User&lt;/h3&gt;<br>          &lt;input type=&quot;text&quot; placeholder=&quot;Username...&quot; className=&quot;input-style&quot; /&gt;<br>        &lt;/Stepper.Content&gt;<br>        <br>        &lt;Stepper.Content index={1}&gt;<br>          &lt;h3 className=&quot;font-bold&quot;&gt;Set Password&lt;/h3&gt;<br>          &lt;input type=&quot;password&quot; placeholder=&quot;****&quot; className=&quot;input-style&quot; /&gt;<br>        &lt;/Stepper.Content&gt;<br>      &lt;/div&gt;<br>    &lt;/Stepper&gt;<br>  );<br>}</pre><h3>Summary</h3><p>How do you tackle prop-drilling in your projects? Let’s discuss different patterns in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd3d8f5655c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Mimarisinde “God Object” Antipattern’inden Kaçınmak: Compound Components]]></title>
            <link>https://medium.com/@sahin.ilyd/react-mimarisinde-god-object-antipatterninden-ka%C3%A7%C4%B1nmak-compound-components-7dd01a20aec7?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd01a20aec7</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 07:53:22 GMT</pubDate>
            <atom:updated>2026-03-31T07:53:22.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Fullstack dünyasında bir özellik geliştirirken hız her şeydir, ancak bazen bu hız bizi “Prop Cehennemi”ne (Prop Drilling/Bloat) sürükler. Bugün, bir Senior React Developer’ın alet çantasındaki en güçlü silahlardan birini, <strong>Compound Component Pattern</strong>’i, ileri seviye tekniklerle inceleyeceğiz.</p><h3>Problem: Esnekliği Öldüren “Monolitik” Componentler</h3><p>Çoğumuzun yaptığı hata, bir componenti tüm senaryolara cevap verecek şekilde tasarlayıp içine onlarca boolean prop (örneğin hasIcon, isSmall, darkTheme) tıkıştırmaktır. Sonuç? 500 satırlık, okunamaz bir dosya ve her yeni istekte bozulan bir mantık.</p><h3>Çözüm: Deklaratif ve Paylaşımlı State</h3><p>Compound Components, bileşenin mantığını ana kapsayıcıda (Parent) tutup, görsel sunumu alt bileşenlere (Children) dağıtır. Aradaki iletişim ise <strong>Context API</strong> ile sessizce halledilir.</p><h3>Profesyonel Uygulama: Stepper Örneği</h3><p>Sadece çalışan bir kod değil, aynı zamanda güvenli ve performanslı bir yapı kuralım.</p><p>TypeScript</p><pre>import React, { <br>  useState, <br>  createContext, <br>  useContext, <br>  useMemo, <br>  useCallback, <br>  ReactNode <br>} from &#39;react&#39;;</pre><pre>// --- TİPLEME ---<br>interface StepperContextProps {<br>  activeStep: number;<br>  goTo: (step: number) =&gt; void;<br>  next: () =&gt; void;<br>}</pre><pre>const StepperContext = createContext&lt;StepperContextProps | undefined&gt;(undefined);</pre><pre>// --- CUSTOM HOOK (Hata Yönetimi İçin) ---<br>function useStepper() {<br>  const context = useContext(StepperContext);<br>  if (!context) {<br>    throw new Error(&#39;Stepper bileşenleri &lt;Stepper /&gt; dışında render edilemez!&#39;);<br>  }<br>  return context;<br>}</pre><pre>// --- ANA COMPONENT ---<br>export function Stepper({ children, initialStep = 0 }: { children: ReactNode; initialStep?: number }) {<br>  const [activeStep, setActiveStep] = useState(initialStep);</pre><pre>  const goTo = useCallback((step: number) =&gt; setActiveStep(step), []);<br>  const next = useCallback(() =&gt; setActiveStep(prev =&gt; prev + 1), []);</pre><pre>  // Performance Optimization: Context değerini memoize ederek <br>  // gereksiz re-render&#39;ların önüne geçiyoruz.<br>  const value = useMemo(() =&gt; ({ activeStep, goTo, next }), [activeStep, goTo, next]);</pre><pre>  return (<br>    &lt;StepperContext.Provider value={value}&gt;<br>      &lt;div className=&quot;stepper-container border rounded-lg p-4 shadow-sm&quot;&gt;<br>        {children}<br>      &lt;/div&gt;<br>    &lt;/StepperContext.Provider&gt;<br>  );<br>}</pre><pre>// --- ALT BİLEŞENLER (Namespace Pattern) ---</pre><pre>const Trigger = ({ index, children }: { index: number; children: ReactNode }) =&gt; {<br>  const { activeStep, goTo } = useStepper();<br>  const isActive = activeStep === index;</pre><pre>  return (<br>    &lt;button<br>      onClick={() =&gt; goTo(index)}<br>      className={`px-4 py-2 rounded transition ${<br>        isActive ? &#39;bg-indigo-600 text-white&#39; : &#39;bg-gray-100&#39;<br>      }`}<br>    &gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>};</pre><pre>const Content = ({ index, children }: { index: number; children: ReactNode }) =&gt; {<br>  const { activeStep } = useStepper();<br>  return activeStep === index ? &lt;div className=&quot;mt-4 py-2&quot;&gt;{children}&lt;/div&gt; : null;<br>};</pre><pre>// Alt bileşenleri ana bileşene bağlayarak temiz bir import sağlıyoruz<br>Stepper.Trigger = Trigger;<br>Stepper.Content = Content;</pre><h3>Neden Bu Yapı “Senior” Bir Yaklaşımdır?</h3><ul><li><strong>Inversion of Control (Kontrolün Tersine Çevrilmesi):</strong> Tasarımı kullanıcıya bırakıyoruz. Trigger butonunu ister üste koyar, ister alta, ister bir div içine alır.</li><li><strong>Memoization:</strong> useMemo ve useCallback kullanımı, büyük ölçekli uygulamalarda render maliyetini minimize eder.</li><li><strong>Strict Context Check:</strong> Custom hook kullanarak, bu bileşenin yanlışlıkla context dışında kullanılmasını engelliyoruz; bu da “Runtime Error”ları önleyen proaktif bir yaklaşımdır.</li></ul><h3>Gerçek Hayat Kullanımı</h3><p>Bu yapıyla, araya istediğiniz Tailwind sınıflarını veya ek HTML etiketlerini hiçbir prop karmaşası yaşamadan ekleyebilirsiniz:</p><p>TypeScript</p><pre>function SignupForm() {<br>  return (<br>    &lt;Stepper initialStep={0}&gt;<br>      &lt;div className=&quot;flex gap-4 border-b pb-2&quot;&gt;<br>        &lt;Stepper.Trigger index={0}&gt;1. Adım&lt;/Stepper.Trigger&gt;<br>        &lt;Stepper.Trigger index={1}&gt;2. Adım&lt;/Stepper.Trigger&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div className=&quot;content-wrapper bg-slate-50 p-4 rounded&quot;&gt;<br>        &lt;Stepper.Content index={0}&gt;<br>          &lt;h3&gt;Kullanıcı Oluştur&lt;/h3&gt;<br>          &lt;input type=&quot;text&quot; placeholder=&quot;Kullanıcı adı...&quot; className=&quot;input-style&quot; /&gt;<br>        &lt;/Stepper.Content&gt;<br>        <br>        &lt;Stepper.Content index={1}&gt;<br>          &lt;h3&gt;Şifre Belirle&lt;/h3&gt;<br>          &lt;input type=&quot;password&quot; placeholder=&quot;****&quot; className=&quot;input-style&quot; /&gt;<br>        &lt;/Stepper.Content&gt;<br>      &lt;/div&gt;<br>    &lt;/Stepper&gt;<br>  );<br>}</pre><h3>Özet</h3><p>Compound Components deseni, UI Kitlerinizi (Modal, Dropdown, Tabs, Stepper) kütüphane seviyesinde esnek hale getirmenin en temiz yoludur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd01a20aec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-World JWT Authentication with Spring Boot + React]]></title>
            <link>https://medium.com/@sahin.ilyd/real-world-jwt-authentication-with-spring-boot-react-9bf481b77a93?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bf481b77a93</guid>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 07:35:53 GMT</pubDate>
            <atom:updated>2026-03-30T07:35:53.571Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Access token, refresh token, role-based guard — an architecture that actually works in production. From scratch, copy-paste ready.</em></blockquote><p><strong>Java 21 · Spring Boot 3.3 · React 18 · TypeScript</strong></p><h3>Architecture Overview</h3><p>We use two tokens: a short-lived accessToken (15 min) and a long-lived refreshToken (7 days). When the access token expires, React automatically calls the refresh endpoint — the user notices nothing.</p><pre>React Client  →  JwtFilter  →  SecurityChain  →  Controller<br>                     ↓<br>             token is validated<br>                     ↓<br>             set into SecurityContext</pre><blockquote><em>💡 Store the refresh token in an </em><strong><em>HttpOnly cookie</em></strong><em>, never in localStorage. This is the only real defense against XSS attacks.</em></blockquote><h3>1. Spring Boot Backend</h3><h3>Dependencies — pom.xml</h3><pre>&lt;!-- Spring Security --&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;!-- JJWT 0.12.6 --&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>  &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>  &lt;version&gt;0.12.6&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>  &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>  &lt;version&gt;0.12.6&lt;/version&gt;<br>  &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>  &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>  &lt;version&gt;0.12.6&lt;/version&gt;<br>  &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>application.yml</h3><pre>app:<br>  jwt:<br>    secret: ${JWT_SECRET}            # env variable — never hardcode!<br>    access-expiration-ms: 900000     # 15 minutes<br>    refresh-expiration-ms: 604800000 # 7 days</pre><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/authdb<br>    username: ${DB_USER}<br>    password: ${DB_PASSWORD}<br>  jpa:<br>    hibernate:<br>      ddl-auto: validate             # use validate in production!<br>    show-sql: false</pre><h3>JwtService.java</h3><pre>@Service<br>public class JwtService {</pre><pre>    @Value(&quot;${app.jwt.secret}&quot;)<br>    private String secretKey;</pre><pre>    @Value(&quot;${app.jwt.access-expiration-ms}&quot;)<br>    private long accessExpMs;</pre><pre>    @Value(&quot;${app.jwt.refresh-expiration-ms}&quot;)<br>    private long refreshExpMs;</pre><pre>    private SecretKey signingKey() {<br>        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));<br>    }</pre><pre>    public String generateAccessToken(UserDetails user) {<br>        return buildToken(user, accessExpMs);<br>    }</pre><pre>    public String generateRefreshToken(UserDetails user) {<br>        return buildToken(user, refreshExpMs);<br>    }</pre><pre>    private String buildToken(UserDetails user, long expMs) {<br>        return Jwts.builder()<br>            .subject(user.getUsername())<br>            .issuedAt(new Date())<br>            .expiration(new Date(System.currentTimeMillis() + expMs))<br>            .signWith(signingKey())<br>            .compact();<br>    }</pre><pre>    public String extractUsername(String token) {<br>        return Jwts.parser()<br>            .verifyWith(signingKey())<br>            .build()<br>            .parseSignedClaims(token)<br>            .getPayload()<br>            .getSubject();<br>    }</pre><pre>    public boolean isTokenValid(String token, UserDetails user) {<br>        final var username = extractUsername(token);<br>        return username.equals(user.getUsername()) &amp;&amp; !isExpired(token);<br>    }</pre><pre>    private boolean isExpired(String token) {<br>        return Jwts.parser()<br>            .verifyWith(signingKey())<br>            .build()<br>            .parseSignedClaims(token)<br>            .getPayload()<br>            .getExpiration()<br>            .before(new Date());<br>    }<br>}</pre><h3>JwtAuthFilter.java</h3><pre>@Component<br>@RequiredArgsConstructor<br>public class JwtAuthFilter extends OncePerRequestFilter {</pre><pre>    private final JwtService jwtService;<br>    private final UserDetailsService userDetailsService;</pre><pre>    @Override<br>    protected void doFilterInternal(HttpServletRequest request,<br>                                    HttpServletResponse response,<br>                                    FilterChain chain)<br>            throws ServletException, IOException {</pre><pre>        final String authHeader = request.getHeader(&quot;Authorization&quot;);</pre><pre>        if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>            chain.doFilter(request, response);<br>            return;<br>        }</pre><pre>        final String token = authHeader.substring(7);<br>        final String username = jwtService.extractUsername(token);</pre><pre>        if (username != null<br>                &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {</pre><pre>            var userDetails = userDetailsService.loadUserByUsername(username);</pre><pre>            if (jwtService.isTokenValid(token, userDetails)) {<br>                var authToken = new UsernamePasswordAuthenticationToken(<br>                    userDetails, null, userDetails.getAuthorities()<br>                );<br>                authToken.setDetails(<br>                    new WebAuthenticationDetailsSource().buildDetails(request)<br>                );<br>                SecurityContextHolder.getContext().setAuthentication(authToken);<br>            }<br>        }</pre><pre>        chain.doFilter(request, response);<br>    }<br>}</pre><h3>SecurityConfig.java</h3><pre>@Configuration<br>@EnableWebSecurity<br>@RequiredArgsConstructor<br>public class SecurityConfig {</pre><pre>    private final JwtAuthFilter jwtAuthFilter;<br>    private final UserDetailsService userDetailsService;</pre><pre>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        return http<br>            .csrf(AbstractHttpConfigurer::disable)<br>            .cors(cors -&gt; cors.configurationSource(corsSource()))<br>            .sessionManagement(sm -&gt; sm.sessionCreationPolicy(STATELESS))<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>                .requestMatchers(&quot;/api/admin/**&quot;).hasRole(&quot;ADMIN&quot;)<br>                .anyRequest().authenticated())<br>            .authenticationProvider(authProvider())<br>            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)<br>            .build();<br>    }</pre><pre>    @Bean<br>    public CorsConfigurationSource corsSource() {<br>        var config = new CorsConfiguration();<br>        // Replace with your real domain in production<br>        config.setAllowedOrigins(List.of(&quot;http://localhost:5173&quot;));<br>        config.setAllowedMethods(List.of(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;));<br>        config.setAllowedHeaders(List.of(&quot;*&quot;));<br>        config.setAllowCredentials(true); // required for HttpOnly cookies<br>        var source = new UrlBasedCorsConfigurationSource();<br>        source.registerCorsConfiguration(&quot;/**&quot;, config);<br>        return source;<br>    }</pre><pre>    @Bean<br>    public AuthenticationProvider authProvider() {<br>        var p = new DaoAuthenticationProvider();<br>        p.setUserDetailsService(userDetailsService);<br>        p.setPasswordEncoder(passwordEncoder());<br>        return p;<br>    }</pre><pre>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><h3>AuthController.java</h3><pre>@RestController<br>@RequestMapping(&quot;/api/auth&quot;)<br>@RequiredArgsConstructor<br>public class AuthController {</pre><pre>    private final AuthService authService;</pre><pre>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;AuthResponse&gt; login(@RequestBody LoginRequest req,<br>                                              HttpServletResponse response) {<br>        var result = authService.login(req);</pre><pre>        // Write refresh token into HttpOnly cookie<br>        var cookie = ResponseCookie.from(&quot;refreshToken&quot;, result.refreshToken())<br>            .httpOnly(true)<br>            .secure(true)       // HTTPS required<br>            .sameSite(&quot;Strict&quot;)<br>            .path(&quot;/api/auth/refresh&quot;)<br>            .maxAge(Duration.ofDays(7))<br>            .build();</pre><pre>        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());<br>        return ResponseEntity.ok(new AuthResponse(result.accessToken(), result.user()));<br>    }</pre><pre>    @PostMapping(&quot;/refresh&quot;)<br>    public ResponseEntity&lt;AuthResponse&gt; refresh(<br>            @CookieValue(name = &quot;refreshToken&quot;, required = false) String refreshToken) {</pre><pre>        if (refreshToken == null)<br>            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();</pre><pre>        return ResponseEntity.ok(authService.refresh(refreshToken));<br>    }</pre><pre>    @PostMapping(&quot;/logout&quot;)<br>    public ResponseEntity&lt;Void&gt; logout(HttpServletResponse response) {<br>        var expired = ResponseCookie.from(&quot;refreshToken&quot;, &quot;&quot;)<br>            .httpOnly(true).secure(true)<br>            .path(&quot;/api/auth/refresh&quot;).maxAge(0).build();<br>        response.addHeader(HttpHeaders.SET_COOKIE, expired.toString());<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><h3>2. React Frontend</h3><p>On the React side, two things must be right: keep the accessToken in memory (not localStorage) and use an <strong>axios interceptor</strong> to silently refresh on every 401.</p><h3>src/lib/axiosClient.ts</h3><pre>import axios, { AxiosInstance } from &#39;axios&#39;;</pre><pre>// Token lives in module scope — NOT in localStorage<br>let accessToken: string | null = null;</pre><pre>export const setAccessToken = (t: string | null) =&gt; { accessToken = t; };</pre><pre>const api: AxiosInstance = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  withCredentials: true, // required to send HttpOnly cookie<br>});</pre><pre>// Attach Bearer token to every request<br>api.interceptors.request.use((config) =&gt; {<br>  if (accessToken)<br>    config.headers.Authorization = `Bearer ${accessToken}`;<br>  return config;<br>});</pre><pre>// On 401 → refresh → retry the original request<br>api.interceptors.response.use(<br>  (res) =&gt; res,<br>  async (err) =&gt; {<br>    const original = err.config;<br>    if (err.response?.status === 401 &amp;&amp; !original._retry) {<br>      original._retry = true;<br>      try {<br>        const { data } = await api.post(&#39;/auth/refresh&#39;);<br>        setAccessToken(data.accessToken);<br>        original.headers.Authorization = `Bearer ${data.accessToken}`;<br>        return api(original); // replay the failed request<br>      } catch {<br>        setAccessToken(null);<br>        window.location.replace(&#39;/login&#39;);<br>      }<br>    }<br>    return Promise.reject(err);<br>  }<br>);</pre><pre>export default api;</pre><h3>src/context/AuthContext.tsx</h3><pre>import { createContext, useContext, useState, useEffect } from &#39;react&#39;;<br>import api, { setAccessToken } from &#39;@/lib/axiosClient&#39;;</pre><pre>interface User {<br>  id: number;<br>  email: string;<br>  role: string;<br>}</pre><pre>interface AuthCtx {<br>  user: User | null;<br>  login: (email: string, password: string) =&gt; Promise&lt;void&gt;;<br>  logout: () =&gt; Promise&lt;void&gt;;<br>}</pre><pre>const AuthContext = createContext&lt;AuthCtx&gt;(null!);</pre><pre>export function AuthProvider({ children }: { children: React.ReactNode }) {<br>  const [user, setUser] = useState&lt;User | null&gt;(null);</pre><pre>  // Restore session on page refresh via cookie<br>  useEffect(() =&gt; {<br>    api.post&lt;{ accessToken: string; user: User }&gt;(&#39;/auth/refresh&#39;)<br>      .then(({ data }) =&gt; {<br>        setAccessToken(data.accessToken);<br>        setUser(data.user);<br>      })<br>      .catch(() =&gt; setUser(null));<br>  }, []);</pre><pre>  const login = async (email: string, password: string) =&gt; {<br>    const { data } = await api.post(&#39;/auth/login&#39;, { email, password });<br>    setAccessToken(data.accessToken);<br>    setUser(data.user);<br>  };</pre><pre>  const logout = async () =&gt; {<br>    await api.post(&#39;/auth/logout&#39;); // clears cookie server-side<br>    setAccessToken(null);<br>    setUser(null);<br>  };</pre><pre>  return (<br>    &lt;AuthContext.Provider value={{ user, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>}</pre><pre>export const useAuth = () =&gt; useContext(AuthContext);</pre><h3>src/components/ProtectedRoute.tsx</h3><pre>import { Navigate, Outlet } from &#39;react-router-dom&#39;;<br>import { useAuth } from &#39;@/context/AuthContext&#39;;</pre><pre>interface Props {<br>  allowedRoles?: string[];<br>}</pre><pre>export default function ProtectedRoute({ allowedRoles }: Props) {<br>  const { user } = useAuth();</pre><pre>  if (!user) return &lt;Navigate to=&quot;/login&quot; replace /&gt;;</pre><pre>  if (allowedRoles &amp;&amp; !allowedRoles.includes(user.role))<br>    return &lt;Navigate to=&quot;/unauthorized&quot; replace /&gt;;</pre><pre>  return &lt;Outlet /&gt;;<br>}</pre><h3>src/App.tsx — Router</h3><pre>&lt;Routes&gt;<br>  &lt;Route path=&quot;/login&quot; element={&lt;LoginPage /&gt;} /&gt;</pre><pre>  {/* Any authenticated user */}<br>  &lt;Route element={&lt;ProtectedRoute /&gt;}&gt;<br>    &lt;Route path=&quot;/&quot;        element={&lt;Dashboard /&gt;} /&gt;<br>    &lt;Route path=&quot;/profile&quot; element={&lt;Profile   /&gt;} /&gt;<br>  &lt;/Route&gt;</pre><pre>  {/* ADMIN only */}<br>  &lt;Route element={&lt;ProtectedRoute allowedRoles={[&#39;ADMIN&#39;]} /&gt;}&gt;<br>    &lt;Route path=&quot;/admin&quot; element={&lt;AdminPanel /&gt;} /&gt;<br>  &lt;/Route&gt;<br>&lt;/Routes&gt;</pre><h3>Before Going to Production</h3><p># Action 1 Persist refresh tokens in the <strong>database</strong> so you can invalidate them on logout or suspicious activity. 2 Enforce <strong>HTTPS</strong> everywhere — staging included. HttpOnly cookies over plain HTTP are meaningless. 3 Add <strong>rate limiting</strong> on /auth/login and /auth/refresh (Bucket4j or Redis). 4 Apply <strong>token rotation</strong> — issue a new refresh token on every refresh call and invalidate the old one. 5 Restrict /actuator/** to ADMIN role or disable it entirely in production.</p><blockquote><em>⚠️ Never go to production with </em><em>ddl-auto: create or </em><em>update. Use </em><strong><em>Flyway</em></strong><em> or </em><strong><em>Liquibase</em></strong><em> — otherwise one day it will drop your table and you&#39;ll have a very bad time.</em></blockquote><h3>Conclusion</h3><p>The combination of refresh token rotation, HttpOnly cookies and an axios interceptor will hold up in production for years. Next up: <strong>Flyway database migrations with Spring Boot</strong> and <strong>server state management with React Query</strong>.</p><p><em>Tags: Spring Boot · React · JWT · Spring Security · TypeScript · Fullstack · Java · Authentication · Axios</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bf481b77a93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot + React ile Gerçek Dünya JWT Authentication]]></title>
            <link>https://medium.com/@sahin.ilyd/spring-boot-react-ile-ger%C3%A7ek-d%C3%BCnya-jwt-authentication-81ea100d056c?source=rss-34bcb7b93442------2</link>
            <guid isPermaLink="false">https://medium.com/p/81ea100d056c</guid>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[İlayda ŞAHİN]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 07:34:52 GMT</pubDate>
            <atom:updated>2026-03-30T07:34:52.213Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Access token, refresh token, role-based guard — production’da gerçekten çalışan mimari. Sıfırdan, kopyala-yapıştır hazır.</em></blockquote><p><strong>Java 21 · Spring Boot 3.3 · React 18 · TypeScript</strong></p><h3>Mimari Genel Bakış</h3><p>İki token kullanıyoruz: kısa ömürlü accessToken (15 dk) ve uzun ömürlü refreshToken (7 gün). Access token expire olunca React tarafı otomatik olarak refresh endpoint&#39;ini çağırır — kullanıcı hiçbir şey fark etmez.</p><pre>React Client  →  JwtFilter  →  SecurityChain  →  Controller<br>                     ↓<br>             token doğrulanır<br>                     ↓<br>             SecurityContext&#39;e set edilir</pre><blockquote><em>💡 Refresh token’ı </em><strong><em>HttpOnly cookie</em></strong><em>’de sakla, localStorage’da değil. XSS saldırılarına karşı tek gerçek savunma bu.</em></blockquote><h3>1. Spring Boot Backend</h3><h3>Dependencies — pom.xml</h3><pre>&lt;!-- Spring Security --&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;!-- JJWT 0.12.6 --&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>  &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>  &lt;version&gt;0.12.6&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>  &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>  &lt;version&gt;0.12.6&lt;/version&gt;<br>  &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>  &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>  &lt;version&gt;0.12.6&lt;/version&gt;<br>  &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h3>application.yml</h3><pre>app:<br>  jwt:<br>    secret: ${JWT_SECRET}            # env variable — asla hardcode etme!<br>    access-expiration-ms: 900000     # 15 dakika<br>    refresh-expiration-ms: 604800000 # 7 gün</pre><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/authdb<br>    username: ${DB_USER}<br>    password: ${DB_PASSWORD}<br>  jpa:<br>    hibernate:<br>      ddl-auto: validate             # production&#39;da validate kullan!<br>    show-sql: false</pre><h3>JwtService.java</h3><pre>@Service<br>public class JwtService {</pre><pre>    @Value(&quot;${app.jwt.secret}&quot;)<br>    private String secretKey;</pre><pre>    @Value(&quot;${app.jwt.access-expiration-ms}&quot;)<br>    private long accessExpMs;</pre><pre>    @Value(&quot;${app.jwt.refresh-expiration-ms}&quot;)<br>    private long refreshExpMs;</pre><pre>    private SecretKey signingKey() {<br>        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));<br>    }</pre><pre>    public String generateAccessToken(UserDetails user) {<br>        return buildToken(user, accessExpMs);<br>    }</pre><pre>    public String generateRefreshToken(UserDetails user) {<br>        return buildToken(user, refreshExpMs);<br>    }</pre><pre>    private String buildToken(UserDetails user, long expMs) {<br>        return Jwts.builder()<br>            .subject(user.getUsername())<br>            .issuedAt(new Date())<br>            .expiration(new Date(System.currentTimeMillis() + expMs))<br>            .signWith(signingKey())<br>            .compact();<br>    }</pre><pre>    public String extractUsername(String token) {<br>        return Jwts.parser()<br>            .verifyWith(signingKey())<br>            .build()<br>            .parseSignedClaims(token)<br>            .getPayload()<br>            .getSubject();<br>    }</pre><pre>    public boolean isTokenValid(String token, UserDetails user) {<br>        final var username = extractUsername(token);<br>        return username.equals(user.getUsername()) &amp;&amp; !isExpired(token);<br>    }</pre><pre>    private boolean isExpired(String token) {<br>        return Jwts.parser()<br>            .verifyWith(signingKey())<br>            .build()<br>            .parseSignedClaims(token)<br>            .getPayload()<br>            .getExpiration()<br>            .before(new Date());<br>    }<br>}</pre><h3>JwtAuthFilter.java</h3><pre>@Component<br>@RequiredArgsConstructor<br>public class JwtAuthFilter extends OncePerRequestFilter {</pre><pre>    private final JwtService jwtService;<br>    private final UserDetailsService userDetailsService;</pre><pre>    @Override<br>    protected void doFilterInternal(HttpServletRequest request,<br>                                    HttpServletResponse response,<br>                                    FilterChain chain)<br>            throws ServletException, IOException {</pre><pre>        final String authHeader = request.getHeader(&quot;Authorization&quot;);</pre><pre>        if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>            chain.doFilter(request, response);<br>            return;<br>        }</pre><pre>        final String token = authHeader.substring(7);<br>        final String username = jwtService.extractUsername(token);</pre><pre>        if (username != null<br>                &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) {</pre><pre>            var userDetails = userDetailsService.loadUserByUsername(username);</pre><pre>            if (jwtService.isTokenValid(token, userDetails)) {<br>                var authToken = new UsernamePasswordAuthenticationToken(<br>                    userDetails, null, userDetails.getAuthorities()<br>                );<br>                authToken.setDetails(<br>                    new WebAuthenticationDetailsSource().buildDetails(request)<br>                );<br>                SecurityContextHolder.getContext().setAuthentication(authToken);<br>            }<br>        }</pre><pre>        chain.doFilter(request, response);<br>    }<br>}</pre><h3>SecurityConfig.java</h3><pre>@Configuration<br>@EnableWebSecurity<br>@RequiredArgsConstructor<br>public class SecurityConfig {</pre><pre>    private final JwtAuthFilter jwtAuthFilter;<br>    private final UserDetailsService userDetailsService;</pre><pre>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        return http<br>            .csrf(AbstractHttpConfigurer::disable)<br>            .cors(cors -&gt; cors.configurationSource(corsSource()))<br>            .sessionManagement(sm -&gt; sm.sessionCreationPolicy(STATELESS))<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/api/auth/**&quot;).permitAll()<br>                .requestMatchers(&quot;/api/admin/**&quot;).hasRole(&quot;ADMIN&quot;)<br>                .anyRequest().authenticated())<br>            .authenticationProvider(authProvider())<br>            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)<br>            .build();<br>    }</pre><pre>    @Bean<br>    public CorsConfigurationSource corsSource() {<br>        var config = new CorsConfiguration();<br>        config.setAllowedOrigins(List.of(&quot;http://localhost:5173&quot;)); // Vite default<br>        config.setAllowedMethods(List.of(&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;OPTIONS&quot;));<br>        config.setAllowedHeaders(List.of(&quot;*&quot;));<br>        config.setAllowCredentials(true); // HttpOnly cookie için şart<br>        var source = new UrlBasedCorsConfigurationSource();<br>        source.registerCorsConfiguration(&quot;/**&quot;, config);<br>        return source;<br>    }</pre><pre>    @Bean<br>    public AuthenticationProvider authProvider() {<br>        var p = new DaoAuthenticationProvider();<br>        p.setUserDetailsService(userDetailsService);<br>        p.setPasswordEncoder(passwordEncoder());<br>        return p;<br>    }</pre><pre>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><h3>AuthController.java</h3><pre>@RestController<br>@RequestMapping(&quot;/api/auth&quot;)<br>@RequiredArgsConstructor<br>public class AuthController {</pre><pre>    private final AuthService authService;</pre><pre>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;AuthResponse&gt; login(@RequestBody LoginRequest req,<br>                                              HttpServletResponse response) {<br>        var result = authService.login(req);</pre><pre>        // Refresh token&#39;ı HttpOnly cookie&#39;ye yaz<br>        var cookie = ResponseCookie.from(&quot;refreshToken&quot;, result.refreshToken())<br>            .httpOnly(true)<br>            .secure(true)<br>            .sameSite(&quot;Strict&quot;)<br>            .path(&quot;/api/auth/refresh&quot;)<br>            .maxAge(Duration.ofDays(7))<br>            .build();</pre><pre>        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());<br>        return ResponseEntity.ok(new AuthResponse(result.accessToken(), result.user()));<br>    }</pre><pre>    @PostMapping(&quot;/refresh&quot;)<br>    public ResponseEntity&lt;AuthResponse&gt; refresh(<br>            @CookieValue(name = &quot;refreshToken&quot;, required = false) String refreshToken) {</pre><pre>        if (refreshToken == null)<br>            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();</pre><pre>        return ResponseEntity.ok(authService.refresh(refreshToken));<br>    }</pre><pre>    @PostMapping(&quot;/logout&quot;)<br>    public ResponseEntity&lt;Void&gt; logout(HttpServletResponse response) {<br>        var expired = ResponseCookie.from(&quot;refreshToken&quot;, &quot;&quot;)<br>            .httpOnly(true).secure(true)<br>            .path(&quot;/api/auth/refresh&quot;).maxAge(0).build();<br>        response.addHeader(HttpHeaders.SET_COOKIE, expired.toString());<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><h3>2. React Frontend</h3><p>React tarafında iki şeyi doğru yapmamız gerekiyor: accessToken&#39;ı bellekte tutmak (localStorage değil) ve her istekte <strong>axios interceptor</strong> ile otomatik refresh yapmak.</p><h3>src/lib/axiosClient.ts</h3><pre>import axios, { AxiosInstance } from &#39;axios&#39;;</pre><pre>// Token modül scope&#39;unda — localStorage&#39;da DEĞİL<br>let accessToken: string | null = null;</pre><pre>export const setAccessToken = (t: string | null) =&gt; { accessToken = t; };</pre><pre>const api: AxiosInstance = axios.create({<br>  baseURL: import.meta.env.VITE_API_URL,<br>  withCredentials: true, // HttpOnly cookie gönderimi için şart<br>});</pre><pre>// Her isteğe Bearer ekle<br>api.interceptors.request.use((config) =&gt; {<br>  if (accessToken)<br>    config.headers.Authorization = `Bearer ${accessToken}`;<br>  return config;<br>});</pre><pre>// 401 → refresh dene → başarısız isteği tekrar gönder<br>api.interceptors.response.use(<br>  (res) =&gt; res,<br>  async (err) =&gt; {<br>    const original = err.config;<br>    if (err.response?.status === 401 &amp;&amp; !original._retry) {<br>      original._retry = true;<br>      try {<br>        const { data } = await api.post(&#39;/auth/refresh&#39;);<br>        setAccessToken(data.accessToken);<br>        original.headers.Authorization = `Bearer ${data.accessToken}`;<br>        return api(original);<br>      } catch {<br>        setAccessToken(null);<br>        window.location.replace(&#39;/login&#39;);<br>      }<br>    }<br>    return Promise.reject(err);<br>  }<br>);</pre><pre>export default api;</pre><h3>src/context/AuthContext.tsx</h3><pre>import { createContext, useContext, useState, useEffect } from &#39;react&#39;;<br>import api, { setAccessToken } from &#39;@/lib/axiosClient&#39;;</pre><pre>interface User {<br>  id: number;<br>  email: string;<br>  role: string;<br>}</pre><pre>interface AuthCtx {<br>  user: User | null;<br>  login: (email: string, password: string) =&gt; Promise&lt;void&gt;;<br>  logout: () =&gt; Promise&lt;void&gt;;<br>}</pre><pre>const AuthContext = createContext&lt;AuthCtx&gt;(null!);</pre><pre>export function AuthProvider({ children }: { children: React.ReactNode }) {<br>  const [user, setUser] = useState&lt;User | null&gt;(null);</pre><pre>  // Sayfa yenilenince refresh cookie ile session&#39;ı kurtar<br>  useEffect(() =&gt; {<br>    api.post&lt;{ accessToken: string; user: User }&gt;(&#39;/auth/refresh&#39;)<br>      .then(({ data }) =&gt; {<br>        setAccessToken(data.accessToken);<br>        setUser(data.user);<br>      })<br>      .catch(() =&gt; setUser(null));<br>  }, []);</pre><pre>  const login = async (email: string, password: string) =&gt; {<br>    const { data } = await api.post(&#39;/auth/login&#39;, { email, password });<br>    setAccessToken(data.accessToken);<br>    setUser(data.user);<br>  };</pre><pre>  const logout = async () =&gt; {<br>    await api.post(&#39;/auth/logout&#39;); // cookie server tarafında temizlenir<br>    setAccessToken(null);<br>    setUser(null);<br>  };</pre><pre>  return (<br>    &lt;AuthContext.Provider value={{ user, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>}</pre><pre>export const useAuth = () =&gt; useContext(AuthContext);</pre><h3>src/components/ProtectedRoute.tsx</h3><pre>import { Navigate, Outlet } from &#39;react-router-dom&#39;;<br>import { useAuth } from &#39;@/context/AuthContext&#39;;</pre><pre>interface Props {<br>  allowedRoles?: string[];<br>}</pre><pre>export default function ProtectedRoute({ allowedRoles }: Props) {<br>  const { user } = useAuth();</pre><pre>  if (!user) return &lt;Navigate to=&quot;/login&quot; replace /&gt;;</pre><pre>  if (allowedRoles &amp;&amp; !allowedRoles.includes(user.role))<br>    return &lt;Navigate to=&quot;/unauthorized&quot; replace /&gt;;</pre><pre>  return &lt;Outlet /&gt;;<br>}</pre><h3>src/App.tsx — Router Yapısı</h3><pre>&lt;Routes&gt;<br>  &lt;Route path=&quot;/login&quot; element={&lt;LoginPage /&gt;} /&gt;</pre><pre>  {/* Giriş yapmış herkes */}<br>  &lt;Route element={&lt;ProtectedRoute /&gt;}&gt;<br>    &lt;Route path=&quot;/&quot;        element={&lt;Dashboard /&gt;} /&gt;<br>    &lt;Route path=&quot;/profile&quot; element={&lt;Profile   /&gt;} /&gt;<br>  &lt;/Route&gt;</pre><pre>  {/* Sadece ADMIN */}<br>  &lt;Route element={&lt;ProtectedRoute allowedRoles={[&#39;ADMIN&#39;]} /&gt;}&gt;<br>    &lt;Route path=&quot;/admin&quot; element={&lt;AdminPanel /&gt;} /&gt;<br>  &lt;/Route&gt;<br>&lt;/Routes&gt;</pre><h3>Production’a Almadan Önce</h3><p># Yapılacak 1 Refresh token’ı <strong>veritabanında</strong> sakla — logout veya şüpheli aktivitede geçersiz kılabilirsin. 2 <strong>HTTPS</strong> zorunlu olsun — hem production hem staging. HttpOnly cookie HTTP’de anlamsız. 3 /auth/login ve /auth/refresh&#39;e <strong>rate limiting</strong> ekle (Bucket4j veya Redis). 4 Her refresh&#39;te <strong>token rotation</strong> yap — yeni refresh token üret, eskisini geçersiz kıl. 5 /actuator/**&#39;ı ADMIN role&#39;üne kilitle ya da production&#39;da tamamen kapat.</p><blockquote><em>⚠️ </em><em>ddl-auto: create veya </em><em>update ile production&#39;a gitme. </em><strong><em>Flyway</em></strong><em> veya </em><strong><em>Liquibase</em></strong><em> kullan — yoksa bir gün tabloyu drop eder ve gerçek bir kabusa dönüşür.</em></blockquote><h3>Sonuç</h3><p>Refresh token rotation, HttpOnly cookie ve axios interceptor üçlüsü production’da yıllar boyu sağlam çalışır. Sonraki bölümde <strong>Flyway migration</strong> ve <strong>React Query ile server state yönetimi</strong> konularını ele alacağız.</p><p><em>Etiketler: Spring Boot · React · JWT · Spring Security · TypeScript · Fullstack · Java · Authentication · Axios</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ea100d056c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>