<?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 Tripop Torcheep on Medium]]></title>
        <description><![CDATA[Stories by Tripop Torcheep on Medium]]></description>
        <link>https://medium.com/@mrtripop?source=rss-2341d7a8ba4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RMkP7rO-_LM-TEz9FIOyHQ.jpeg</url>
            <title>Stories by Tripop Torcheep on Medium</title>
            <link>https://medium.com/@mrtripop?source=rss-2341d7a8ba4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:01:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrtripop/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[System Architecture — Diagrams]]></title>
            <link>https://medium.com/@mrtripop/my-engineering-journey-system-architecture-a69cdda7b856?source=rss-2341d7a8ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a69cdda7b856</guid>
            <category><![CDATA[diagrams]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tripop Torcheep]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 18:56:42 GMT</pubDate>
            <atom:updated>2026-06-07T05:45:46.301Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Engineer ไม่ว่ายุคก่อนหรือตอนนี้ System Architect ยังเป็นหัวใจเสมอ บทความนี้จะเล่าถึง Diagram ที่ผมใช้ครับ</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KEZ6oulnP-1EN6qzNijww.png" /></figure><p>สวัสดีครับ ชายครับ 🫡 ขณะนี้ทำงานเป็น Software Engineer อยู่ที่ Lotus’s</p><p>ชายเขียนบทความนี้เพื่อเก็บรวบรวมประสบการณ์ สิ่งที่ได้เจอมา สิ่งที่ต้องปรับปรุง และทริคเล็กๆน้อยๆสำหรับย้ำเตือนตัวเองในอนาคตเวลาเจอปัญหาคล้ายๆกันครับ (ถ้าเป็นประโยชน์กับคนอื่นๆได้ก็ยินดีนะครับ 😋)</p><h3>ซีรีย์นี้มีหลายพาร์ท ไปตำกันได้!</h3><ol><li>System Architecture</li><li>Performance Analysis</li><li>Performance Testing &amp; Metrics</li><li>วัดผลด้วยข้อมูล (No gut feeling)</li><li>เทคนิคจูน Legacy System</li><li>(โบนัส) สิ่งที่ทำผิดพลาด</li></ol><h3><strong>ทำไมต้องมี System Architecture</strong></h3><p>เคยถูกมอบหมายให้รับช่วงต่อโปรเจคจากทีมอื่นไหมครับ? เวลาต้องเริ่มต้นกับระบบใหม่ แรกๆจะมีคำถามเยอะเลย ฉันต้องเริ่มจากตรงไหน? ระบบนี้ทำงานยังไง? การไหลข้อมูลเป็นยังไง? หรือถ้าต้องแก้เรื่องนี้ต้องไปดูตรงไหน?</p><p>เวลาต้องรับช่วงต่อ สิ่งแรกที่ผมคาดหวังมากที่สุดคือ <strong><em>System Architecture &amp; Document </em></strong>อย่างน้อยๆไม่เห็น Flowchart ก็ควรเห็น High-Level กับ Data Flow (ขอล่ะ)</p><p>ซึ่งถ้าไม่ได้อะไรมาเลย (น่าเศร้าใจนะ) เราก็ไม่ควรปล่อยผ่านครับ อยากให้เราๆทุกคนทำ Diagram ขึ้นมาเพื่อเป็นประโยชน์ทั้งกับตัวเองและคนอื่นๆ เช่น น้องๆ Junior หรือเพื่อนพนักงานใหม่</p><p>สกิลเหล่านี้จะใช้ในการวิเคราะห์ระบบ ปัญหาแปลกๆ หรือหาจุดที่ระบบสามารถปรับปรุงได้ น้องๆ Junior ควรฝึกนะครับ สิ่งนี้ดีกับ Career Path ของเราแน่นอน</p><p>โดย Tools หลักๆที่ผมใช้วาดจะมี 2 อย่างคือ Miro กับ Draw.io</p><h3>ผมดันมี Pain Point กับ Diagram</h3><p>ผมเจอ Pain Point อยู่อันนึงคือ ถ้าคนวาดไม่รู้จะสื่อสารอะไร วาดไปงั้นๆแค่ให้มีหรือแค่เสร็จ สุดท้าย Diagram จะไร้ประโยชน์ครับ ถ้าไม่สามารถสื่อสารสิ่งที่ควรจะสื่อ</p><p>ผมเห็น Diagram มากมาย ที่ไม่มีคนดู ไม่มีคนใช้ (แม้แต่คนวาดเอง) ทำแบบนี้เสียเวลาเปล่าครับ เพราะสิ่งที่ควรได้จาก Diagram คือความสามารถในการวิเคราะห์ ถ้าทำแล้วยังงงเหมือนเดิม นั่นแปลว่าเราไม่ได้เข้าใจเลยครับ</p><p>ดังนั้นผมจะขอเล่าวิธีคิดและวิธีเลือกใช้ Diagram ฉบับของผมในการทำ Visualize สิ่งต่างๆที่ผมต้องการจะสื่อ</p><blockquote>ปล. ไม่มี Story telling! ส่วนใหญ่คนดู diagram ผมจะเป็น Tech อยู่แล้ว แค่เห็นก็อ๋อกันได้เองแล้ว 555+</blockquote><h3><strong>ผมใช้ Diagram อะไรบ้าง</strong></h3><p>ส่วนตัวผมชอบใช้ <strong><em>High-Level Diagram (C4) </em></strong>กับ <strong><em>Swimlane</em></strong><em> </em><strong><em>Diagram </em></strong>เพราะทำให้คนใน/นอกทีมเห็นภาพได้ง่ายที่สุด</p><p>สังเกตจาก Reaction เวลาอธิบาย Architect คำถามง่ายๆที่เคยถูกถามมักจะมีน้อยลงหรือไม่มีเลย ทำให้ได้ถกประเด็นในเรื่องที่เป็น Gap มากขึ้น</p><p>แต่บางเวลาก็จะมี <strong>Custom Diagram</strong> เพื่อใช้วิเคราะห์เฉพาะงานครับ</p><h4><strong>High-Level Diagram (C4 Model)</strong></h4><p>ผมเอาไว้ทำความเข้าใจภาพรวม end-to-end ของระบบ เช่น ผู้ใช้ทำ Action อะไรข้อมูลไหลผ่านระบบอะไรบ้าง กว่าจะออกมาเป็น Business Operation อันนึง</p><p>C4 จะช่วยให้เข้าใจภาพใหญ่ แล้วค่อยๆย่อยลงเรื่อยๆ มีทั้งหมด 4 ระดับคือ Context, Container, Component, และ Code</p><p>ผมเปรียบ 4 ระดับนี้เป็นเหมือนการ Zoom-in, Zoom-out คือสามารถเห็นภาพกว้างได้ว่าระบบหลังบ้านของบริษัทเรามีอะไรบ้าง ทำงานด้วยกันยังไง และย่อยไปจนถึงภาพ sub-system ว่าใช้ Database, Cache, Message Queue, หรือ Third-party API ตัวไหนอยู่บ้างจาก Diagram เดียว</p><p><strong>Context Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oxh9XUrmQZSt4u_5eQMcUw.png" /><figcaption>สมมุติตัวอย่างระบบการเงินประเภท Payment Gateway</figcaption></figure><blockquote>ตัวอย่างภาพนี้ผมคิดไวๆ ซึ่งถ้าจะเอาไปใช้จริง diagram นี้ควรจะมีการรีวิว เพื่อให้เข้าใจ Context ตรงกันนะครับ</blockquote><p>จากรูปจะเห็นผู้เกี่ยวข้องและ Key Activity</p><ul><li>Merchant เป็นผู้ให้บริการ เช่น Shopping online platform ซึ่งใช้บริการ Third-Party Payment Gateway ในการรับชำระเงินของลูกค้า</li><li>Customer เป็นลูกค้าของ Merchant เมื่อ Customer ซื้อของแล้วต้องการจ่ายเงิน ระบบของ Merchant จะขอข้อมูลในการทำรายการจาก Payment Gateway และให้ลูกค้าโอนเงินไปที่ๆ Payment Gateway กำหนด</li><li>จากนั้นจะเป็น Process ภายในของ Payment Gateway จนกระทั่ง Transaction สำเร็จ จึงส่งแจ้งเตือนไปหา Merchant เพื่อบอกว่า Customer จ่ายเงินเรียบร้อยแล้ว Merchant จึงเริ่มทำการส่งของที่ Customer สั่งได้</li><li>โดยเบื้องหลังจะมีทีม Operation Staff คอยมอนิเตอร์และแก้ไขเมื่อเกิดปัญหาภายในระบบ Payment Gateway อีกที</li></ul><p>ถึงตรงนี้จะเห็น Context กับการใช้งานหลักของระบบครับ ซึ่งอันนี้จะเป็น High-Level ซึ่งเราจะ Deep Dive ลงไปอีกหน่อยด้วย Container Diagram</p><p><strong>Container Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RQyEY-47qA9BH-Vt2qbeg.png" /></figure><p>ตัวอย่างนี้ผมก็คิดง่ายๆว่าให้ระบบ Payment Gateway มี Admin Dashboard, Mobile App, และ Backend API (1 service) สำหรับให้ Merchant เข้ามาใช้งานและมอนิเตอร์ยอดเงิน <a href="https://miro.com/templates/c4-architecture/">โดยผม custom คร่าวๆจาก template นี้</a></p><p>จากรูปนี้จะเริ่มเน้นหนักที่ส่วนประกอบพื้นฐานที่ประกอบกันจนออกมาเป็นระบบ Payment Gateway, กำหนดหน้าที่ ความรับผิดชอบของแต่ละกล่อง, และรวมถึง Protocol ในการคุยกัน</p><p>ซึ่งถ้า API Application เราอาจแยกย่อยเป็นมากกว่า 1 Service เราสามารถแยกกล่อง Diagram นี้ได้เลย และกำหนดวิธีในการคุยกันให้ชัดเจนครับ</p><p><strong>Component Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dkql9L9v0i4jQ1_tHX_CFQ.png" /></figure><p>ตัวอย่างนี้ผมก็คิด Feature ที่ควรจะมีขึ้นมาแบบไวๆอีก Diagram นี้จะเป็นภาพขยายของ <strong>API Application</strong> ซึ่งจะระบุ Feature ทั้งส่วนของ Functional และ Non-Functional ให้ออกมาเป็นก้อนๆและกำหนดหน้าที่ให้ครับ</p><p>Diagram นี้จะมีการเปลี่ยนแปลงบ่อยที่สุดตามจำนวน Feature ที่เยอะขึ้นของ Service นั้นๆ และจะมีความยุ่งเหยิงพอสมควรครับ ดังนั้นผมจะใส่แค่ Component หลักๆเท่านั้น</p><p>พอถึง Diagram นี้เราก็จะเห็นภาพชัดขึ้นว่า API Application มี Core Feature อะไรบ้าง ซึ่งจะใช้มองภาพรวมว่าตอนนี้ขาดอะไรที่จำเป็นอีกบ้าง</p><blockquote>หลังจากนี้ก็จะเป็น Code Diagram ซึ่งปกติผมไม่ลงถึงขั้นนั้นครับ เพราะ Layer นั้นมักใช้ Swimlane ร่วมกับหลักการ SOLID หรือ Design Pattern ต่างๆในการจัดการโค้ดแทนอยู่แล้ว และมีการเปลี่ยนแปลงบ่อย เช่น ปรับ Logic, เพิ่ม Feature, Refactor ซึ่งถ้าเราทำ Diagram มันจะ Not Sync ง่ายมากครับ</blockquote><h3>Custom Diagram</h3><p>C4 model ด้านบนจะช่วยให้เราเห็น Architecture โดยรวมว่ามีอะไรบ้าง แต่สิ่งที่ C4 ยังไม่กระจ่างซะทีเดียวในเชิง Technical เช่น Parallel processing หรือ Rotate Database Secret แบบไม่มี downtime ทำงานยังไงเป็นต้น</p><p>ดังนั้นผมจะชอบทำ Custom diagram ขึ้นมาเสมอ (เพราะเป็น Engineer แค่ทำ Architect ได้นิดหน่อย 🤣) เพื่ออธิบาย behavior เหล่านั้น เช่น คอขวดแปลกๆ App ไม่ได้ใช้ Resource เต็มที่แต่ Throughput ดันต่ำ ทั้งๆที่เราก็โค้ดเป็น Parallel แล้ว</p><p>ซึ่งงานที่เกี่ยวข้องกับ Performance tuning ผมจะใช้ Diagram นี้เป็นตัวช่วยวิเคราะห์ (ถึงหลายครั้งจะไม่ได้วาด แต่จะมองภาพเป็นประมาณนี้ครับ)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7ZfniIkHdowZ4ueB-Orcg.png" /><figcaption>High level system and data flow</figcaption></figure><p>อย่างในรูปจะเห็นว่า consumer A ดูแล Kafka topic 4 partitions ซึ่ง consumer A อาจเป็นคอขวดตอนโหลดสูงๆ เนื่องจาก CPU, Memory, หรือ Logic ดังนั้นจึงเอาข้อมูลตรงนี้มาออกแบบ Test Scene เช่น</p><ul><li>ลองสเกล consumer A ขึ้นเป็น 2 pods และดูแล pod ละ 2 partitions จะเป็นอย่างไร (สปอย: ถ้า Consumer เป็น Sequential Process ประสบการณ์ส่วนตัว Throughput จะไม่เพิ่มอย่างมีนัยยะสำคัญครับ แม้จะเพิ่ม Max poll แล้ว)</li><li>ลองเพิ่ม Partitions จาก 4 partitions เป็น 8 partitions และ 1 pod ดูแล 8 partitions จะเป็นอย่างไร (เคสนี้ผมไม่ได้ลองเพราะ Theory แล้วต้องเพิ่มขึ้น แต่ก็แลกด้วย Storage และการจัดการของ DevOps แต่การเพิ่ม Partitions เรื่อยๆผมคิดว่าไม่เหมาะเป็น Long-term solution เท่าไหร่)</li></ul><p>Diagram จะบอกในเชิงของ Process ว่ามีการการกระจายงานแค่ไหน มีคอขวดที่จุดนี้หรือไม่ ซึ่งถ้าตรงนี้ผ่านหมด ไม่มีอะไรที่คาดว่าจะทำให้เป็นคอขวด Action ถัดมาผมจะใช้ Swimlane เป็นตัวช่วยในการ Zoom-In ลอจิกครับ</p><p><strong>Swimlane Diagram (Consumer A)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yk1sWjgrfgmaUNLCqCj_0w.png" /><figcaption>ตัวอย่าง Swimlane ที่ใช้ Visualize Process &amp; Dependency</figcaption></figure><p>Diagram นี้ช่วยให้ผมเข้าใจ Process และ Dependency ของ Consumer A ชัดขึ้น รวมถึงใช้อ้างอิงในการเตรียม Data Test หรือการ Stub 3rd API ได้ด้วย</p><p>ทั้งหมดทำให้ผมสื่อสารกับทีมได้ง่ายขึ้น พอทุกคนเห็นภาพตรงกัน เราสามารถถกในส่วนงานที่จะทำใน Sprint ได้ง่ายขึ้น เช่น ต้องการทำ Performance Tuning, ปัจจุบัน Architect &amp; Process เป็นยังไง, Next step ทำอะไร, ผลลัพธ์ในเชิง Theory ควรเป็นแบบไหน ทำนองนี้ครับ</p><h3><strong>Cloud Architecture Diagram</strong></h3><p>ทีนี้ถ้าเราเอาทุกอย่าง เช่น Kubernetes, Database, Kafka ไว้บน Cloud เดียวกัน C4 &amp; Swimlane ก็น่าจะเพียงพอแล้ว แต่ถ้าโจทย์เป็น Multi-Cloud จะต้องมี Factor ให้พิจารณาเพิ่มเติมอีกหน่อย ซึ่งผมก็ไม่ได้เชี่ยวชาญ แต่จะวาด <strong>Hybrid Cloud Architecture Diagram</strong> แบบง่ายๆขึ้นมาครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFt7uw5mc8m9dB9nCopQ_Q.png" /><figcaption>ตัวอย่าง Multi-Cloud Architecture</figcaption></figure><p>เหตุผลที่วาด Diagram นี้เพราะ Factor ที่เราสนใจคือ “<strong>Latency</strong>” ระหว่าง Cloud และค่าใช้จ่ายของ “<strong>Data Transfer</strong>”</p><p>ซึ่งผมใช้ Diagram ประกอบการวิเคราะห์ Latency ต่ำสุดที่เป็นไปได้ รวมถึงค่าใช้จ่ายที่เกิดขึ้นจาก Data Transfer (อ้างอิง Load ปัจจุบันกับขนาดของ Data)</p><p>เช่น ระหว่าง AWS SG กับ Thai Region จะมี network round trip ที่ 30ms ซึ่งต่อให้เรา Optimize Query ได้เร็วสุดๆที่ 32ms มันก็จะไม่ต่ำกว่า 30ms ครับ</p><h3>Diagram อื่นๆ</h3><p>ยังมี Diagram อีกหลากหลายที่เหมาะกับของแต่ละ Use Case ครับ เช่น</p><p>DevOps อาจใช้ <a href="https://cloudairy.com/blog/understanding-kubernetes-architecture-diagrams-and-components">Kubernetes Architecture Diagrams and Components</a> เป็น Visualize tools ในการทำความเข้าใจว่าแท้จริงๆ Kube มีอะไรประกอบกันบ้าง</p><p>QA ก็อาจจะมี Mind Map หรือ Tree ในการแตกแยกย่อย scenario เพื่อใช้คิด Idea หรือหา Gap ที่ยังไม่ถูกทดสอบได้ (ยังไม่รวม Automate test architecture นะ)</p><p>อยากให้ลองหาอ่าน ฝึกวาด ฝึกใช้กันดูนะครับ</p><h4>แล้วคุณล่ะวาด Diagram ยังไงในยุค AI ??</h4><p>หลายๆครั้งมี Diagram เยอะๆมันก็วาดไม่ไหวเนอะ ยิ่ง Swimlane ของแต่ละ Process แบบละเอียดยิบนี่ยิ่งยากเลย</p><p>Engineer อย่างเราๆถูกจ้างมาให้ทำโปรดักจริงๆ ไม่ใช่วาด Diagram ดังนั้นเวลาส่วนใหญ่ของเราจะไม่ได้อยู่กับงานพวกนี้ เลยจะชอบเกิดเคส Diagram ไม่อัพเดต</p><p>ซึ่งจากปัญหาตรงนี้ และความเก่งของ AI ผมกำลังตามหา Skill หรือ Workflow ที่จะทำให้มัน automate ด้านนี้ให้อยู่ครับ AI Skill ที่ผมกำลังทดลองใช้สร้าง Diagram จะมีของ Draw.io กับ Excalidraw</p><ul><li><a href="https://github.com/jgraph/drawio-mcp">https://github.com/jgraph/drawio-mcp</a></li><li><a href="https://github.com/coleam00/excalidraw-diagram-skill">https://github.com/coleam00/excalidraw-diagram-skill</a></li></ul><p>ซึ่งผลลัพธ์ของการลองก็ไม่แย่ แต่ก็ยังไม่ใช่แบบที่ต้องการเท่าไหร่ครับ ผลลัพธ์ประมาณนี้</p><blockquote>แรกๆมามันจะเส้นซ้อนทับกันเยอะเลย แต่ผมปรับให้มันเข้าทีนิดหน่อยครับ ใช้เวลา 1–2 นาที แต่ไม่ได้รีวิวความถูกต้องนะครับ แค่ทดสอบ Style (ผมชอบแบบที่ผมวาดด้านบนมากกว่า 5555)</blockquote><h4>Draw.io</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGFzDLOvhxwVTURGZnEaHw.png" /></figure><p>สุดท้ายก็การทำ Diagram Update &amp; Versioning ก็ยังเป็นเรื่องที่ Challenge ใครมี ไอเดียหรือประสบการณ์ในการแก้ปัญหาเรื่องนี้ Comment เข้ามาแชร์กันได้นะ รออ่านของทุกๆคนครับ</p><p>Happy Learning!</p><h3>References</h3><ul><li><a href="https://c4model.com/">https://c4model.com/</a></li><li><a href="https://miro.com/templates/c4-architecture/">https://miro.com/templates/c4-architecture/</a></li><li><a href="https://cloudairy.com/blog/cloud-infrastructure-architecture-diagram">https://cloudairy.com/blog/cloud-infrastructure-architecture-diagram</a></li><li><a href="https://mikelopster.dev/posts/diagram-basic/">https://mikelopster.dev/posts/diagram-basic/</a></li><li><a href="https://cloudairy.com/blog/understanding-kubernetes-architecture-diagrams-and-components">https://cloudairy.com/blog/understanding-kubernetes-architecture-diagrams-and-components</a></li><li><a href="https://www.drawio.com/docs/diagram-types/">https://www.drawio.com/docs/diagram-types/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a69cdda7b856" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สรุป Rate Limit — Part 1]]></title>
            <link>https://medium.com/@mrtripop/%E0%B8%AA%E0%B8%A3%E0%B8%B8%E0%B8%9B-rate-limit-part-1-c2da32db6fab?source=rss-2341d7a8ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2da32db6fab</guid>
            <category><![CDATA[rate-limit]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Tripop Torcheep]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 17:25:03 GMT</pubDate>
            <atom:updated>2024-07-07T17:25:03.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>สรุป Rate Limit — Part 1</h3><p>สวัสดีครับ วันนี้ชายจะพาทุกคนมารู้จักกับ Rate Limit ซึ่งหลายๆคนอาจเคยทำงานกับ Third party ที่มีการตั้ง Rate limit การใช้ APIs เอาไว้ ซึ่งก็อาจมีคำถามว่า Rate Limit คืออะไร? ทำ Rate Limit ไปทำไม?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2U0xqOWlADz-H62qWO_6w.png" /></figure><h3>Rate Limit คืออะไร ?</h3><p>Rate limit เป็นการกำหนดจำนวนครั้งที่ผู้ใช้สามารถเข้าถึง resources หรือบริการต่างๆภายในระยะเวลาที่กำหนด เช่น service อนุญาตให้ผู้ใช้สามารถเข้าถึง APIs ได้ 100 request ต่อชั่วโมง ถ้ามากกว่านั้น reject เป็นต้น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iIRiFD6j5VppFAGWYIuxQ.png" /></figure><p>โดยการทำ Rate limit อาจจะอยู่บนพื้นฐาน เช่น</p><ol><li>จำนวนของ operation เช่น 20 request ต่อวินาที</li><li>จำนวนของ data เช่น 2 GB ต่อนาที</li><li>และอีกมากมาย</li></ol><p>สิ่งเหล่านี้จะเป็น metrics หรือตัวบ่งบอกว่าเมื่อไหร่จะมีการติด Rate limit ของผู้ใช้</p><h3>ทำไมต้องทำ Rate Limit?</h3><p>Rate limit นั้นมีประโยชน์ในหลากหลายด้านเลย ดังนั้นจะขอพูดในหลายๆบริบทครับว่าทำไมเราควรจะต้องทำ Rate limit(แต่ไม่จำเป็นต้องใช้กับทุกอย่างนะครับ)</p><h4><strong>บริบทในเชิง Business</strong></h4><p>สมมุติว่าเรามี service ให้บริการลูกค้าเป็นแบบ subscription รายเดือนๆละ 200 บาท ซึ่งลูกค้ามีการทำ batch operation กับ service ของเรา โดยระบบของเรารองรับได้ประมาณ 100 request ต่อวินาที</p><p>และเครื่อง server ของเราที่รันอยู่มีจำนวนและค่าใช้จ่ายที่คุ้มกับจำนวนผู้ใช้แล้ว ซึ่งก็ happy ดี เพราะลูกค้าทั้งหมดใช้บริการรวมกันไม่เกิน 100 request ต่อวินาที ดังภาพด้านล่างครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHQh7d3yaQZS2D3ADZlrrg.png" /></figure><p>แต่แล้ววันนึงมีลูกค้าหัวใส ทำ batch operation เข้ามามากกว่าปกติ ดังรูป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTRgQGqHG9gUuKhLczFDLQ.png" /></figure><p>ซึ่งเหตุการณ์แบบนี้ ถ้าบริษัทของเรามีเงินก็แค่เพิ่ม server เพื่อมาจัดการกับปัญหานี้และเป็น cost เพิ่มเติมของบริษัทที่ต้องจ่าย แต่อย่างกรณีที่กล่าวไว้ตอนแรกว่า server ที่มีอยู่นั้นคุ้มค่ากับจำนวนผู้ใช้แล้ว การเพิ่ม server ดูจะไม่คุ้ม</p><p>ถ้าเรายังคงใช้เครื่อง server เท่าเดิมจะเกิดเหตุการณ์อะไรต่อ? System จะเริ่ม error และ reject request ทำให้ผู้ใช้ท่านอื่นอาจจะโดนแย่ง resource ไปแบบงงๆ ซึ่งไม่โอเคเลยในมุมผู้ใช้ เพราะทุกคนจ่าย 200 บาทต่อเดือนเท่ากัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZfEDklXPSGEC8ltrABghA.png" /></figure><p>เพื่อให้เกิดความเท่าเทียมในการใช้งาน การทำ Rate limit จะสามารถตอบโจทย์เรื่องนี้ได้ โดยถ้าเรากำหนดว่าผู้ใช้แต่ละคนสามารถใช้ได้แค่ 25 req/sec เท่านี้ก็ไม่มีใครสามารถใช้งานเกินที่กำหนดได้แล้วครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7IzDxHlvbUFrLLtsa3wMw.png" /></figure><h4>บริบทในเชิง Technical</h4><p>ปกติ technical จะล้อไปกับ businessโดยผมสมมุติว่าบริษัทเรามีรายได้ต่อเดือน 1,000 บาท โดยเป็นค่าใช้จ่ายของระบบและ operation ต่างๆดังนี้</p><ul><li>ค่า server 200 บาทต่อเดือน</li><li>ค่า database 200 บาทต่อเดือน</li><li>ค่าพนักงาน 400 บาทต่อเดือน</li></ul><p>หักรายจ่ายแล้ว ต่อเดือนจะเหลือกำไร 200 บาท ซึ่งเท่านี้คุ้มค่าที่จะลงทุนแล้ว</p><p>สมมุติจากราคาว่าเป็น database ตัวเล็กที่สามารถจัดการ records ที่เข้ามาได้มากสุด 100 records ต่อวินาที (สมมุติ database เป็นคอขวด)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqU3DM7WPaf2pjv7RWZK4w.png" /></figure><p>จากรูปด้านบน ถ้าผู้ใช้ทำการ request เข้ามาจำนวนมากกว่าที่ database จัดการได้จะเกิดอะไรขึ้น?</p><p>คำตอบคือ database จะเริ่มจัดการกับ records ที่เข้ามาไม่ทัน ทำให้อาจจะเกิด timeout หรือ reject request นั้นในที่สุด สมมุติสถานการณ์เป็นดังภาพด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNa3TbXSmtWqTQ054mhOgQ.png" /></figure><p>จากภาพมี request เข้ามาพร้อมกัน 200 req/sec แต่ database จัดการได้แค่ 100 records/sec ทำให้มี 100 records ที่ถูก reject ซึ่งผู้ใช้มีการ retry กรณี failed<br>ดังนั้น records ที่ถูก reject จะมีการส่งกลับมาอีกครั้งเพื่อทำให้สำเร็จ ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfoYo713xrt0Fg6N0KSw4w.png" /></figure><p>จะเห็นว่าเราต้องทำการส่ง records เดิมซ้ำรวมกันแล้วถึง 300 records ไปให้ database เพื่อ process เพียง 200 records(ตัวอย่างตัวเลขค่อนข้างน้อยครับ)</p><p>เรื่องนี้มีทางออกเท่าที่คิดออกได้ 2 ทาง</p><ol><li>อัพขนาดของ database ขึ้นเพื่อให้จัดการกับ records ได้มากขึ้น</li><li>กำหนด Rate limit การส่ง request เข้ามาเพื่อจำกัดจำนวน records</li></ol><p>แต่จากสถานการณ์สมมุติ เราคงไม่เลือกข้อ 1 ดังนั้นการทำ Rate limit ก็เป็นสิ่งที่ยังตอบโจทย์อยู่ครับ(การทำ Rate limit ไม่ง่ายและไม่ฟรีนะครับ) จะได้ผลลัพธ์ดังภาพ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsZSovcT6dgTLxadV_rd4w.png" /></figure><blockquote>ทั้งนี้ Rate limit ยังมีประโยชน์อีกด้านที่รู้คือด้าน security แต่ขอยังไม่ลง details ครับ</blockquote><h3>Conclusion</h3><p>Rate limit เป็นเครื่องมือที่ดีทั้งในหลายๆแง่ทั้งในด้าน business และ technical แต่ก็ต้องเลือกวางแผนกันมาอย่างดีกับการที่จะเอาเจ้าตัว Rate limit ไปใช้งาน เพราะการ limit ที่ไม่ดีอาจส่งผลกับ user experience ได้ และถ้ามีการใช้ tools ต่างๆก็ต้องมีการ maintain infrasture ด้วย มีดีก็ต้องมีเสีย ควรศึกษาให้ละเอียดก่อนตัดสินใจนะครับ</p><blockquote>ดีใจที่อ่านมาถึงตรงนี้ ขอบคุณครับ</blockquote><h3>References</h3><ul><li><a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/rate-limiting-pattern">Azure Microsoft — Rate Limiting</a></li><li><a href="https://platform.openai.com/docs/guides/rate-limits">OpenAI — Rate Limits</a></li><li><a href="https://www.cloudflare.com/learning/bots/what-is-rate-limiting/">Cloudflare — Rate Limiting</a></li><li><a href="https://java-design-patterns.com/patterns/throttling/">Java Design Pattern — Throttling Pattern in Java</a></li><li><a href="https://life.wongnai.com/%E0%B8%AD%E0%B8%AD%E0%B8%81%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A-rate-limit-%E0%B8%9A%E0%B8%99-distributed-system-efcacc69aec8">ออกแบบระบบ Rate Limit บน Distributed System</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2da32db6fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ลงลึก Java BigDecimal กับการนำไปใช้]]></title>
            <link>https://medium.com/@mrtripop/%E0%B8%A5%E0%B8%87%E0%B8%A5%E0%B8%B6%E0%B8%81-java-bigdecimal-%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%99%E0%B8%B3%E0%B9%84%E0%B8%9B%E0%B9%83%E0%B8%8A%E0%B9%89-51ba998797cf?source=rss-2341d7a8ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/51ba998797cf</guid>
            <category><![CDATA[bigdecimal]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-datatypes]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[bigdecimal-java]]></category>
            <dc:creator><![CDATA[Tripop Torcheep]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 15:36:55 GMT</pubDate>
            <atom:updated>2024-06-22T15:36:55.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuKB9_OTuCfze6zcs3De_Q.jpeg" /></figure><p>แนะนำตัวสั้นๆ สวัสดีครับ ผมชื่อ…<strong>ชาย</strong>!… ก่อนหน้านี้ผมได้เกริ่นพื้นฐานเกี่ยวกับการใช้เจ้า <strong>BigDecimal</strong> ไปแล้ว ดังนั้นวันนี้เราจะมาลงลึกเกี่ยวกับเจ้า Data Type ตัวนี้ในการเอาไปใช้งานจริงกันซักหน่อย</p><p>สำหรับใครที่ยังไม่ได้อ่านบทความที่แล้ว สามารถไปตามกันได้ที่นี่</p><p><a href="https://medium.com/@mrtripop/%E0%B8%97%E0%B8%B3%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%88%E0%B8%B1%E0%B8%81%E0%B8%81%E0%B8%B1%E0%B8%9A-bigdecimal%E0%B9%83%E0%B8%99-java-%E0%B8%81%E0%B8%B1%E0%B8%99-a8fe3cd26640">ทำความรู้จักกับ BigDecimalใน Java กัน</a></p><h3>โจทย์วันนี้เราจะมาลองทำระบบฝาก-ถอนเงินกัน</h3><p>เนื่องจากระบบธนาคารจะใช้ทศนิยมประมาณ 2 หลัก (ธนาคาร Crypto ค่อยทีหลังนะครับ ทศนิยมมันกว่า Fait มากๆ)โดยจะจำลองสถานการณ์ง่ายๆ เช่น</p><ul><li>เมี่อ user ฝากเงินระบบจะต้องทำการจดบันทึก transaction ว่า ยอดเงินเดิมของ user มีเท่าไหร่ ฝากเพิ่มเข้ามาเป็นเท่าไหร่ และยอดล่าสุดเป็นเท่าไหร่</li><li>เมื่อ user ถอนเงินระบบจะต้องทำการจดบันทึก transaction ว่ายอดเงินเดิมของ user มีเท่าไหร่ เพียงพอหรือไม่ ถอนออกไปเท่าไหร่ และยอดล่าสุดเป็นเท่าไหร่</li></ul><p>เนื่องจากเป็นระบบทางการเงิน เรื่องตัวเลขและความแม่นยำของตัวเลขจึงสำคัญมากๆ คงไม่มีใครอยากให้เกิด case ที่ว่าฝากเงินเข้าแล้วยอดลดลงกว่าที่ควรจะเป็นเนอะ (แต่ถ้ายอดเพิ่ม user ก็จะยิ้มๆหน่อย แต่ธนาคารน่าจะกุมขมับ 555)</p><h3>เริ่มทดลองกัน</h3><p>ผมจะเริ่มจากเขียน Class ขึ้นมา 1 อันชื่อว่า UserBalance ซึ่งจะเป็นคลาสที่มียอดเงินของลูกค้าเก็บไว้นะครับ และจะมี method ง่ายๆชื่อว่า deposit และ withdraw ครับ</p><blockquote>มีการ validate input เพื่อป้องกัน user ใส่ input ที่มันไม่สามารถทำได้จริงเข้ามาครับ เช่น deposit ด้วยตัวเลขที่ติดลบ เป็นต้น</blockquote><p>ในส่วนของ data model ผมจะออกแบบง่ายๆประมาณนี้เพื่อเป็นตัวอย่าง</p><pre>import jakarta.persistence.*;<br>import lombok.AllArgsConstructor;<br>import lombok.Builder;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>@Data<br>@Entity<br>@Table(name = &quot;user_balances&quot;)<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class UserBalance {<br><br>  @Id<br>  @GeneratedValue(strategy = GenerationType.SEQUENCE)<br>  private Long id;<br><br>  private String name;<br>  private Double balance;<br>}</pre><p>เพื่อเพิ่มความ single responsibility จึงแยกเอา operation ที่ใช้คำนวณตัวเลขมาไว้ที่ UserBalanceOperation</p><pre>public class UserBalanceOperation {<br><br>  private final UserBalance userBalance;<br><br>  public UserBalanceOperation(UserBalance userBalance) {<br>    this.userBalance = userBalance;<br>  }<br><br>  public UserBalance deposit(double amount) throws Exception {<br>    validateInputNumber(amount);<br>    double updatedBalance = userBalance.getBalance() + amount;<br>    return new UserBalance(userBalance.getId(), userBalance.getName(), updatedBalance);<br>  }<br><br>  public UserBalance withdraw(double amount) throws Exception {<br>    validateInputNumber(amount);<br>    inputCanWithdraw(amount);<br>    double currentBalance = userBalance.getBalance() - amount;<br>    return new UserBalance(userBalance.getId(), userBalance.getName(), currentBalance);<br>  }<br><br>  private void validateInputNumber(double amount) throws Exception {<br>    if (amount &lt; 0) throw new Exception(&quot;User deposit/withdrawal amount is negative&quot;);<br>    if (amount == 0) throw new Exception(&quot;User deposit/withdrawal amount cannot be zero&quot;);<br>  }<br><br>  private void inputCanWithdraw(double amount) throws Exception {<br>    if (userBalance.getBalance() &lt; amount) {<br>      throw new Exception(&quot;Current user balance cannot withdraw for &quot; + amount + &quot; baths&quot;);<br>    }<br>  }<br>}</pre><p>โอเค ก่อนหน้านี้เรามี data model กับ operation แล้วถัดมาเพื่อตรวจสอบความถูกต้องผมจะทำการพิสูจน์ scenario ต่างๆด้วย Unit Testing ซึ่งถ้าดูจาก code ด้านบนผมจะมีประมาณ 7 scenario</p><ol><li><strong>[Success]</strong> ยอดเงินปัจจุบัน 0, มียอดฝากคือ 200 บาท คาดหวังยอดเงินปัจจุบันเป็น 200 บาท</li><li><strong>[Failed]</strong> ยอดเงินปัจจุบัน 200, มียอดฝากคือ -50 บาท คาดหวังว่าจะต้องมี error มาบอก user</li><li><strong>[Failed] </strong>ยอดเงินปัจจุบัน 0, มียอดฝากคือ 0 บาท คาดหวังว่าจะต้องมี error มา<br>บอก user</li><li><strong>[Success]</strong> ยอดเงินปัจจุบัน 200, มียอดถอนคือ 50 บาท คาดหวังว่ายอดเงินปัจจุบันเป็น 150 บาท</li><li><strong>[Failed]</strong> ยอดเงินปัจจุบัน 150, มียอดถอนคือ -50 บาท คาดหวังว่าจะต้องมี error มาบอก user</li><li><strong>[Failed] </strong>ยอดเงินปัจจุบัน 0, มียอดถอนคือ 50 บาท คาดหวังว่าจะต้องมี error มาบอก user</li><li><strong>[Failed] </strong>ยอดเงินปัจจุบัน 0, มียอดถอนคือ 0 บาท คาดหวังว่าจะต้องมี error มา<br>บอก user</li></ol><p>แล้วนี่ก็คือ Code Unit Test ที่ผมได้ทำการเขียนขึ้นมาอ้างอิง scenario ด้านบน</p><pre>@ExtendWith(MockitoExtension.class)<br>class UserBalanceOperationTest {<br><br>  @Mock private UserBalance currentBalance;<br><br>  @InjectMocks private UserBalanceOperation userBalanceOperation;<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0, deposit 200 baths&quot;)<br>  void success_the_user_current_balance_is_0_deposit_200_baths() throws Exception {<br>    // arrange<br>    double userDeposit = 200.0;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.0);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.deposit(userDeposit);<br>    // assert<br>    assertEquals(200.0, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[FAILED] The user&#39;s deposit -50 baths, receive error response&quot;)<br>  void failed_the_user_deposit_minus_50_baths_receive_error_response() {<br>    // arrange<br>    double userDeposit = -50.0;<br>    // action<br>    Exception exception =<br>        assertThrows(Exception.class, () -&gt; userBalanceOperation.deposit(userDeposit));<br>    // assert<br>    assertEquals(&quot;User deposit/withdrawal amount is negative&quot;, exception.getMessage());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[FAILED] The user&#39;s deposit 0 baths, receive error response&quot;)<br>  void failed_the_user_deposit_0_baths_receive_error_response() {<br>    // arrange<br>    double userDeposit = 0.0;<br>    // action<br>    Exception exception =<br>        assertThrows(Exception.class, () -&gt; userBalanceOperation.deposit(userDeposit));<br>    // assert<br>    assertEquals(&quot;User deposit/withdrawal amount cannot be zero&quot;, exception.getMessage());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 200, withdraw 50 baths&quot;)<br>  void success_the_user_current_balance_is_200_withdraw_50_baths() throws Exception {<br>    // arrange<br>    double userWithdraw = 50.0;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(200.0);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.withdraw(userWithdraw);<br>    // assert<br>    assertEquals(150.0, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[FAILED] The user&#39;s withdraw -50 baths, receive error response&quot;)<br>  void failed_the_user_withdraw_minus_50_baths_receive_error_response() {<br>    // arrange<br>    double userWithdraw = -50.0;<br>    // action<br>    Exception exception =<br>        assertThrows(Exception.class, () -&gt; userBalanceOperation.withdraw(userWithdraw));<br>    // assert<br>    assertEquals(&quot;User deposit/withdrawal amount is negative&quot;, exception.getMessage());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[FAILED] The user&#39;s current balance is 0, withdraw 50 baths&quot;)<br>  void failed_the_user_current_balance_is_0_withdraw_50_baths() {<br>    // arrange<br>    double userWithdraw = 50.0;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.0);<br>    // action<br>    Exception exception =<br>        assertThrows(Exception.class, () -&gt; userBalanceOperation.withdraw(userWithdraw));<br>    // assert<br>    assertEquals(&quot;Current user balance cannot withdraw for 50.0 baths&quot;, exception.getMessage());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[FAILED] The user&#39;s withdraw 0 baths, receive error response&quot;)<br>  void failed_the_user_withdraw_0_baths_receive_error_response() {<br>    // arrange<br>    double userWithdraw = 0.0;<br>    // action<br>    Exception exception =<br>        assertThrows(Exception.class, () -&gt; userBalanceOperation.withdraw(userWithdraw));<br>    // assert<br>    assertEquals(&quot;User deposit/withdrawal amount cannot be zero&quot;, exception.getMessage());<br>  }<br>}</pre><p>และนี่คือผลลัพธ์หลังจากทดสอบแล้วครับ ~ โอเร่! จุดเริ่มต้นของเราเสร็จไปด้วยดี</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLJT_0ErWyx8rccXdNM7lg.png" /></figure><p>แต่จะมี case สำหรับ verify ความถูกต้องของการคำนวณโดยเฉพาะอีก ดังนั้น case เหล่านี้เราจะคาดหวังว่ามันจะ <strong>success</strong> เท่านั้น โดยผมได้ให้ ChatGPT ช่วยหา scenario ที่จะมาพิสูจน์ความถูกต้องของการคำนวณ โดยได้จะมี scenario ตามนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVMQj9W6YogHg6jVmXIAlw.png" /></figure><p>ในสกุลเงินปกติเราจะไม่ค่อยเห็นใครโอนเงินให้ใครด้วยยอด 0.1, 0.2 กันเนอะ แต่ในโลกของ Crypto ตัวเลขพวกนี้เราเห็นกันเป็นปกติเลยครับ ดังนั้นพวกการคำนวณตัวเลขของธนาคารต้องแม่นๆนิดนึง</p><p>โอเค มาลองเขียน unit test สำหรับ deposit/withdrawal ด้วย scenario เหล่านี้กันครับโดยผมจะเริ่มจาก proof ก่อนว่าตัวเลขตาม scenario ด้านบนนั้นผิดจริงมั้ย และนี่คือ code unit test</p><pre>@ExtendWith(MockitoExtension.class)<br>public class BalanceCalculationTest {<br>  @Mock private UserBalance currentBalance;<br><br>  @InjectMocks private UserBalanceOperation userBalanceOperation;<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0.1, deposit 0.2 baths&quot;)<br>  void success_the_user_current_balance_is_0_1_deposit_0_2_baths() throws Exception {<br>    // arrange<br>    double userDeposit = 0.2;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.1);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.deposit(userDeposit);<br>    // assert<br>    assertEquals(0.3, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0.1, deposit 0.7 baths&quot;)<br>  void success_the_user_current_balance_is_0_1_deposit_0_7_baths() throws Exception {<br>    // arrange<br>    double userDeposit = 0.7;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.1);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.deposit(userDeposit);<br>    // assert<br>    assertEquals(0.8, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0.7, deposit 0.2 baths&quot;)<br>  void success_the_user_current_balance_is_0_7_deposit_0_2_baths() throws Exception {<br>    // arrange<br>    double userDeposit = 0.2;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.7);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.deposit(userDeposit);<br>    // assert<br>    assertEquals(0.9, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0.3, withdraw 0.1 baths&quot;)<br>  void success_the_user_current_balance_is_0_3_withdraw_0_1_baths() throws Exception {<br>    // arrange<br>    double userWithdraw = 0.1;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.3);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.withdraw(userWithdraw);<br>    // assert<br>    assertEquals(0.2, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0.5, withdraw 0.4 baths&quot;)<br>  void success_the_user_current_balance_is_0_5_withdraw_0_4_baths() throws Exception {<br>    // arrange<br>    double userWithdraw = 0.4;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.5);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.withdraw(userWithdraw);<br>    // assert<br>    assertEquals(0.1, updatedUserBalance.getBalance());<br>  }<br><br>  @Test<br>  @DisplayName(&quot;[SUCCESS] The user&#39;s current balance is 0.8, withdraw 0.6 baths&quot;)<br>  void success_the_user_current_balance_is_0_8_withdraw_0_6_baths() throws Exception {<br>    // arrange<br>    double userWithdraw = 0.6;<br>    // stub<br>    when(currentBalance.getBalance()).thenReturn(0.8);<br>    // action<br>    UserBalance updatedUserBalance = userBalanceOperation.withdraw(userWithdraw);<br>    // assert<br>    assertEquals(0.2, updatedUserBalance.getBalance());<br>  }<br>}</pre><p>และผลลัพธ์หลังจากทดสอบก็คือทุกเคสผลลัพธ์ออกมาผิดทั้งหมด (สาเหตุมาจาก floating-point number limitation ในระบบคอมพิวเตอร์ครับ)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3YhDMIcE6aC3Cwhr6dPUg.png" /></figure><p>ทีนี้จะต้องแก้ยังไง? ใช่ไหมครับ อย่างที่ผมเกริ่นไปตั้งแต่ต้น <strong>BigDecimal </strong>จะเข้ามาตอบโจทย์สำหรับคนที่ใช้ Java ครับ (สำหรับภาษาอื่นขออภัย)</p><p>ผมจะเริ่มจาก Refactor คลาส UserBalanceOperation ซักหน่อย โดยจะนำเอา BigDecimal เข้ามาปรับใช้นิดหน่อยครับ</p><pre>public class UserBalanceOperation {<br><br>  private final UserBalance userBalance;<br><br>  public UserBalanceOperation(UserBalance userBalance) {<br>    this.userBalance = userBalance;<br>  }<br><br>  public UserBalance deposit(double amount) throws Exception {<br>    validateInputNumber(amount);<br>    BigDecimal userBalanceBigDecimal = BigDecimal.valueOf(userBalance.getBalance());<br>    BigDecimal userDepositAmount = BigDecimal.valueOf(amount);<br>    //    double updatedBalance = userBalance.getBalance() + amount;<br>    double updatedBalance = userBalanceBigDecimal.add(userDepositAmount).doubleValue();<br>    return new UserBalance(userBalance.getId(), userBalance.getName(), updatedBalance);<br>  }<br><br>  public UserBalance withdraw(double amount) throws Exception {<br>    validateInputNumber(amount);<br>    inputCanWithdraw(amount);<br>    BigDecimal userBalanceBigDecimal = BigDecimal.valueOf(userBalance.getBalance());<br>    BigDecimal userDepositAmount = BigDecimal.valueOf(amount);<br>    //    double currentBalance = userBalance.getBalance() - amount;<br>    double updatedBalance = userBalanceBigDecimal.subtract(userDepositAmount).doubleValue();<br>    return new UserBalance(userBalance.getId(), userBalance.getName(), updatedBalance);<br>  }<br><br>  private void validateInputNumber(double amount) throws Exception {<br>    if (amount &lt; 0) throw new Exception(&quot;User deposit/withdrawal amount is negative&quot;);<br>    if (amount == 0) throw new Exception(&quot;User deposit/withdrawal amount cannot be zero&quot;);<br>  }<br><br>  private void inputCanWithdraw(double amount) throws Exception {<br>    if (userBalance.getBalance() &lt; amount) {<br>      throw new Exception(&quot;Current user balance cannot withdraw for &quot; + amount + &quot; baths&quot;);<br>    }<br>  }<br>}</pre><blockquote>จริงๆไม่ควรทำแบบนี้นะ แต่สมมุติเป็นสถานณ์ว่าเรามี software เก่าๆที่ใช้ Double มาตลอดแล้วเรามีหน้าที่ต้องเพิ่มความถูกต้อง แต่ไม่อยากแก้โค้ดให้กระทบทั้งโปรเจค วิธีนี้ก็สามารถนำมาใช้ก่อนได้ แล้วค่อย migrate data type ของ application มาใช้ BigDecimal เรื่อยๆก็ได้</blockquote><p>ทีนี้ผลลัพธ์ก็จะถูกต้องทั้งหมดแล้วครับ</p><ul><li>สำหรับ user scenario ทั่วไป</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qa4dmz7z_8RhD9zMjruUMA.png" /></figure><ul><li>สำหรับ verify calculation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Vemcc4tVay4kdAyVzRPhw.png" /></figure><p>ถึงตรงนี้หลายคนน่าจะเห็นถึงความสำคัญของ BigDecimal กับระบบการเงินแล้ว</p><h3>ทศนิยมไม่จำกัดจัดการด้วย MathContext</h3><p>ก่อนอื่นเราน่าจะคุ้นเคยกับค่า Pi ในคณิตศาสตร์ ซึ่งเป็นค่าที่มีทศนิยมไปเรื่อยๆไม่มีที่สิ้นสุด แต่ในคอมพิวเตอร์นั้นมีจำนวน Bit จำกัด ดังนั้นมันจำเป็นต้องมีจุดสิ้นสุดของเลขทศนิยม</p><blockquote>Pi = 22/7 = 3.14285714286……..ไปเรื่อยๆ</blockquote><p><strong>ตัวอย่าง error</strong></p><pre>@Test<br>@DisplayName(&quot;[POC] Verify assumption about PI in computer&quot;)<br>void poc_verify_assumption_about_PI_in_computer() {<br>  BigDecimal n1 = BigDecimal.valueOf(22);<br>  BigDecimal n2 = BigDecimal.valueOf(7);<br><br>  BigDecimal result = n1.divide(n2);<br><br>  assertEquals(3.14, result.doubleValue());<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ho7u3HYdMvYhWHeYRUjfg.png" /></figure><p>ดังนั้นเราจึงต้องแก้ไขโดยการกำหนดกรอบของตัวเลขให้มี limit อยู่แค่ช่วงๆนึงเท่านั้น เพื่อไม่ให้เกิดปัญหาทศนิยมไปเรื่อยๆไม่สิ้นสุด ซึ่งสามารถกำหนดได้ผ่าน MathContext</p><blockquote><strong>MathContext คืออะไร?</strong></blockquote><blockquote>เป็น Object อันนึงที่ช่วยกำหนด range ของผลลัพธ์ให้เป็นไปตามที่เราคาดหวัง เช่น system ของเราอาจจะต้องการทศนิยมแค่ 6 ตำแหน่ง เราก็สามารถกำหนดให้ผลลัพธ์ออกมาแค่ 6 ตำแหน่งได้ โดยส่วนที่เกินเอาอาจปัดทิ้ง, เกินครึ่งปัดขึ้น, หรือต่ำกว่าครึ่งปัดลง เป็นต้น</blockquote><p>Refactor code ด้านบนซักหน่อย</p><pre>@Test<br>@DisplayName(&quot;[POC] Verify assumption about PI in computer&quot;)<br>void poc_verify_assumption_about_PI_in_computer() {<br>  BigDecimal n1 = BigDecimal.valueOf(22);<br>  BigDecimal n2 = BigDecimal.valueOf(7);<br><br>  BigDecimal result = n1.divide(n2, new MathContext(3, RoundingMode.DOWN));<br><br>  assertEquals(3.14, result.doubleValue());<br>}</pre><p>เรียบร้อย! ผ่านแล้วครับ (จาก code ผมให้มันปัดตัวเลขที่อยู่หลังทศนิยมตำแหน่งที่ 2 ทิ้งหมดเลยครับ)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7cyJOcHO0J4gpDsuQUCoIQ.png" /></figure><h3>Scale คืออะไร? เอาไว้ใช้ทำอะไร?</h3><p>ลองนึกถึงสถานการณ์แบบนี้ครับ third-party ของเราบอกว่าทศนิยมจะมีความแม่นยำไม่เกิน 10 ตำแหน่ง ถ้าเขาเกิดส่งมา 13 ตำแหน่ง ให้เราตัดตั้งแต่ตำแหน่งที่ 11 ทิ้งไป ถ้าเราใช้ Double data type เราจะทำยังไงครับ? — Scale เกิดมาเพื่อทำการนี้</p><p>ถ้าดูจากโค้ดด้านล่าง third-party ส่งค่าอะไรไม่รู้มาเยอะมาก ซึ่งเราต้องการแค่ 10 digit โดยที่ข้างหลังนั้นให้ทิ้ง ก็จะได้จำนวนทศนิยมตามที่เราต้องการแล้วครับ</p><pre>@Test<br>@DisplayName(&quot;[POC] Verify assumption about scale in decimal and rounding mode&quot;)<br>void poc_verify_assumption_about_scale_in_decimal_and_rounding_mode() {<br>  BigDecimal number =<br>      BigDecimal.valueOf(<br>          1.5999842313164864354987949849431321688978979794564564656119818916866846484686484613534846);<br><br>  BigDecimal result = number.setScale(10, RoundingMode.DOWN);<br><br>  assertEquals(1.5999842313, result.doubleValue());<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWGwXtqqnb3NJf1Qe-ahhA.png" /></figure><h3>Strip Trailing Zeros ให้เลขสวยๆซักหน่อย</h3><p>ก่อนจะไปรู้จักกับ stripTrailingZeros() เรามาเข้าใจสถานการณ์กันก่อน สมมุติเรามีเลข 2 ตัวบวกกันแบบนี้</p><blockquote>0.999999 + 0.000001 = 1</blockquote><p>แต่เวลาที่เจ้า BigDecimal คำนวณได้มันจะเป็นแบบนี้ครับ</p><blockquote>0.999999 + 0.000001 = 1.000000</blockquote><p>ถ้าดูจากตัวอย่างโค้ด (ปกติถ้าเรา convert จาก BigDecimal เป็น double ตอนท้ายมันจะไม่มีปัญหานี้ ใน case นี้ผมเลยแสดงเป็นตัวอย่างของ BigDecimal แทน)</p><pre>@Test<br>@DisplayName(&quot;[POC] Verify assumption about strip trailing zeros&quot;)<br>void poc_verify_assumption_about_strip_trailing_zeros() {<br>  BigDecimal n1 = BigDecimal.valueOf(0.999999);<br>  BigDecimal n2 = BigDecimal.valueOf(0.000001);<br><br>  BigDecimal result = n1.add(n2);<br><br>  assertEquals(new BigDecimal(&quot;1&quot;), result);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFa1zmGukUBsdP2LRAhtRg.png" /></figure><p>ซึ่งถ้าเราต้องการจะตัด 0 ที่อยู่ตรงหางออกไป เพื่อให้ตัวเลขมันดูสวยๆ ก็ให้เรียกใช้ฟังก์ชั่น stripTrailingZeros() ได้เลย</p><p>มาลอง refactor code กัน</p><pre>@Test<br>@DisplayName(&quot;[POC] Verify assumption about strip trailing zeros&quot;)<br>void poc_verify_assumption_about_strip_trailing_zeros() {<br>  BigDecimal n1 = BigDecimal.valueOf(0.999999);<br>  BigDecimal n2 = BigDecimal.valueOf(0.000001);<br><br>  BigDecimal result = n1.add(n2).stripTrailingZeros();<br><br>  assertEquals(new BigDecimal(&quot;1&quot;), result);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZGoVluQ7-8rXWQX41tQhw.png" /></figure><p>เรียบร้อยยย! ลงลึกสำหรับ BigDecimal ก็จะมีประมาณนี้เลย อาจจะยังมีเรื่องของ RoundingMode ซึ่งตรงนี้ขึ้นอยู่กับข้อจำกัดของแต่ละที่ ต้อง discuss ตรงนี้กันให้ดีครับ</p><h3>Conclusion</h3><p>BigDecimal เป็นหนึ่งใน data type ที่เหมาะกับ system ที่คำนวณกับตัวเลขที่มีทศนิยมหลายๆตำแหน่งให้ผลลัพธ์ออกมามีความแม่นยำ แต่ก็ต้องพูดตรงๆว่าในระบบคอมพิวเตอร์มันก็ยังมีข้อจำกัดอยู่หลายๆอย่าง ทั้งนี้ BigDecimal ก็ค่อนข้างเพียงพอสำหรับสถานการณ์ปกติ แต่อย่าลืมศึกษาข้อจำกัดการนำไปใช้ด้วยนะครับ</p><blockquote>ขอบคุณทุกท่านที่อ่านมาถึงตรงนี้นะครับ ❤️</blockquote><h3>Reference</h3><ul><li><a href="https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html">Oracle javadocs of BigDecimal class</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html">Oracle javadocs of RoundingModel for BigDecimal</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/math/MathContext.html">Orable javadocs of MathContext for BigDecimal</a></li><li><a href="https://developers.fireblocks.com/reference/balance-decimal-precision">Fireblocks — Balance Decimal Precision</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51ba998797cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ทำความรู้จักกับ BigDecimalใน Java กัน]]></title>
            <link>https://medium.com/@mrtripop/%E0%B8%97%E0%B8%B3%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%88%E0%B8%B1%E0%B8%81%E0%B8%81%E0%B8%B1%E0%B8%9A-bigdecimal%E0%B9%83%E0%B8%99-java-%E0%B8%81%E0%B8%B1%E0%B8%99-a8fe3cd26640?source=rss-2341d7a8ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8fe3cd26640</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[data-type-in-java]]></category>
            <category><![CDATA[bigdecimal]]></category>
            <dc:creator><![CDATA[Tripop Torcheep]]></dc:creator>
            <pubDate>Sun, 12 May 2024 09:02:03 GMT</pubDate>
            <atom:updated>2024-05-12T09:02:03.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRRnokLJp1_V8unk4C0qjg.jpeg" /><figcaption><a href="https://unsplash.com/photos/black-samsung-flat-screen-computer-monitor-LrxSl4ZxoRs">Image from Unsplash</a></figcaption></figure><p>สวัสดีครับ! ถ้าพูดถึง data type ที่ใช้กับตัวเลขจำพวก “<strong>ทศนิยม</strong>” จะคิดถึงอะไรกัน? หลายๆคำตอบคงจะเป็น <strong>double/float</strong> ซึ่งนั่นถูกต้องครับ</p><p>ทีนี้คุณเคยเจอ operation ที่ทำกับเลขทศนิยมแล้วได้ผลลัพธ์ออกมาไม่ตรงกับที่เราคาดหวังไว้รึเปล่า? ตัวอย่างเช่น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bir4iOJ-XT48BcfXuczZvA.png" /></figure><p>จากรูปด้านบน ทุกท่านคนคิดว่าผลลัพธ์จะออกตรงตาม expectation ไหมครับ? <strong>คำตอบคือไม่ครับ!!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*sDh4oYlN0L8oZ-_zy-bwww.png" /></figure><p>อ่าว! แล้วถ้าเป็น float ล่ะจะเป็นเหมือนกันไหม?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4OKFF44LCryKQ34QRdsGw.png" /></figure><p>ผลลัพธ์ที่ได้ก็คือ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*of0jzHqB6xZqVep2GEf4rw.png" /></figure><p>กรรม! นู่นก็เกิน นี่ก็ขาด! ทำไมหล่ะ? มันเกิดอะไรขึ้น? การจะรู้คำตอบของสิ่งนี้คุณจะต้องเข้าใจการทำงานของระบบเลขทศนิยมใน computer ซึ่งนั่นจะยังไม่ใช่หัวข้อที่เราจะคุยกันในวันนี้ ขออุ๊บส์ไว้ก่อนครับ</p><p>กลับมาที่ปัญหาที่เราเจอ ลองนึกภาพว่าความผิดพลาดนี้มันเกิดขึ้นในระบบที่เกี่ยวข้องกับการเงิน ปัญหาคือเงินลูกค้าอาจจะหาย หรือ เงินธนาคารอาจจะหายได้</p><blockquote>ระบบธนาคารที่กล่าวถึงจะเกี่ยวข้องกับ Fiat currency ถ้าพูดถึง Crypto currency จะต้องกังวลเรื่องทศนิยมมากขึ้น เพราะเกี่ยวกับกับทศนิยมหลายตำแหน่งมากกว่า</blockquote><h3>BigDecimal คืออะไร</h3><p>เกริ่นมาเยอะแล้ว solution อะไรที่จะแก้ปัญหานี้ล่ะ? ผมเสนอ 1 ในที่ผมใช้ก็คือ BigDecimal ซึ่งเจ้า BigDecimal จะประกอบด้วย 2 ส่วนหลักๆ</p><ol><li><strong>Unscaled value</strong> — ตัวเลขจำนวนเต็มขนาดใหญ่(arbitrary precision integer)</li><li><strong>Scale</strong> — ตัวเลข 32-bit ที่แสดงถึงจำนวน digit ด้านขวาของเลขทศนิยม</li></ol><p>ปกติแล้วตัวเลขจะถูกจำกัดด้วยจำนวน bit เช่น 32-bit สามารถเก็บค่าได้ตั้งแต่ <strong><em>-2,147,483,648</em></strong> จนถึง <strong><em>2,147,483,647 </em></strong>แต่ถ้าเจอตัวเลขที่มากกว่า range ที่ bit รองรับได้ก็จะเกิดสิ่งที่เรียกว่า overflow ซึ่งส่งผลกับความแม่นยำของ value</p><p>สิ่งที่ BigDecimal ให้เราได้คือ arbitrary precision integer หมายถึงตัวเลขที่มันมีขนาดใหญ่กว่า range ที่รองรับได้ แต่ยังมีความแม่นยำในการเก็บรักษา value</p><p>ด้วยเหตุนี้ BigDecimal จึงเก็บค่าเป็น integer แทนที่จะเป็นทศนิยมครับ แล้วก็จะมี scale เป็นตัวที่บอกว่าเป็นทศนิยมกี่ตำแหน่ง ซึ่งเข้าใจเป็นสมการได้แบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*6ws0IH9E3YlCoEKTN4JyPA.png" /></figure><h3>วิธีใช้ BigDecimal</h3><p>ที่นี้เรามาลองกันครับว่ามันแก้ปัญหาด้านบนที่ผมกล่าวไปได้จริงมั้ย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQ_eJypkKywjL3v5xR72Kg.png" /></figure><p>ผลลัพธ์ที่ได้คือ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*FzCJOqOL2KPkVFesRK0XOg.png" /></figure><p>แอร๊ย ทำไมมันยังผิด??</p><p>เฉลยก็คือ ถ้าเราใช้ท่า construct object(new keyword) ตอนที่เรา construct object เราใช้ number เป็นตัว construct ครับ ทำให้ค่าที่ได้ออกมาไม่แม่นยำ จุดที่ทำให้ผิดคือตรงนี้(ตัวเลข 0.4, 0.3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmLUBRXCFi1SZHYQh3o_Gw.png" /></figure><p>ซึ่งถ้าจะ construct object แบบนี้ ท่าที่แม่นยำกว่าคือใช้ string ในการ contstruct</p><blockquote>หลายๆคนอาจเคยเจอว่า third party เราทำไม response ตัวเลขมาเป็น string ทั้งๆที่ number เอาไปใช้ง่ายกว่าแท้ๆ เหตุผลส่วนหนึ่งก็มาจากเรื่องความแม่นยำครับ</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7ccVk37-zJ-4v3TyKFZEQ.png" /></figure><p>ผลลัพธ์ที่ได้คือ เขียวแล้วครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBmROz7xCn0JJrF6YSw7mg.png" /></figure><p>ซึ่งทีนี้ก็จะมีประเด็นว่าแล้วถ้า third party response มาเป็น double จะให้ทำยังไง?? แน่นอนว่าเราก็มีวิธีครับ คือใช้ BigDecimal.valueOf() นั่นเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-cFvV-3oTyVLrO5RlfUVw.png" /></figure><p>ผลลัพธ์ที่ได้ ก็คือ!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nO04SC9Ff1h85cqPEe7Vg.png" /></figure><h4>Conclusion</h4><p>ตัวเลขด้านบนเป็นแค่ตัวอย่างเท่านั้นครับ ซึ่งตัวเลขเจ้าปัญหามันไม่ได้จบแค่ 0.4–0.3 เท่านั้น มันยังมีหลายๆตัวที่เป็นปัญหาให้เราปวดหัว ซึ่งแน่นอนว่าเราคงไม่ต้องการให้เกิดผลกระทบก่อนแล้วค่อยแก้ ดังนั้นการใช้ BigDecimal ก็เป็นอีก 1 ทางเลือกสำหรับแก้ปัญหาทศนิยมใน Java ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dc18tVtKi9COAnROIv_rA.png" /></figure><p>ถึงตรงนี้มันยังมีภาคต่อนะเออ ถ้าเราต้องทำ operation กับเลขทศนิยมหลายๆตำแหน่ง เช่น 17 ตำแหน่ง จะทำยังไงให้มีความแม่นยำ? แล้วถ้าต้องปัดเศษทศนิยมตำแหน่งที่ 18 ทิ้งไม่ว่าจะเกิน 5 หรือน้อยกว่า 5 ทิ้งล่ะทำยังไง? หรือถ้าต้อง dynamic scale ล่ะทำยังไง?</p><p>ก่อนที่เราจะพบกันในบทความถัดไป ทุกๆอย่างที่ผมอ่าน ผมทิ้ง reference ไว้แล้วสามารถไปหาอ่านกันได้เลย</p><h4>Reference</h4><ul><li><a href="https://stackoverflow.com/questions/12088857/what-is-the-precise-meaning-of-arbitrary-precision#:~:text=With%20arbitrary%20precision%20integers%2C%20the,to%20the%20least%20significant%20unit.">Mean of arbitrary precision integer</a></li><li><a href="https://www.baeldung.com/java-bigdecimal-biginteger">BigInteger and BigDecimal in Java</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html">Oracle javadocs of BigDecimal class</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html">Oracle javadocs of RoundingModel for BigDecimal</a></li></ul><p>ถ้าอ่านมาถึงตรงนี้แล้วชอบ อยากให้มาติดตามกันไว้นะครับ ที่ <a href="https://github.com/mrtripop">GitHub</a> ผมยินดีมากๆที่จะได้ร่วมเรียนรู้และลองทำอะไรใหม่ๆไปกับทุกคนครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8fe3cd26640" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write AWS Lambda with Javascript]]></title>
            <link>https://medium.com/@mrtripop/write-aws-lambda-with-javascript-ebe983be1a08?source=rss-2341d7a8ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe983be1a08</guid>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Tripop Torcheep]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 16:58:38 GMT</pubDate>
            <atom:updated>2023-03-11T17:14:21.989Z</atom:updated>
            <content:encoded><![CDATA[<p>This is tutorial for beginner that work with AWS Lambda by writing code with Javascript language.</p><p>If you need to know some detial of AWS Lambda, please checkout to this article before we start.</p><p><a href="https://medium.com/@tripop.chai12/intro-aws-lambda-%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B9%83%E0%B8%88%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86%E0%B8%81%E0%B8%B1%E0%B8%99-5d58b723cfd">Intro AWS Lambda ให้เข้าใจง่ายๆกัน</a></p><p><strong>Prerequisite</strong></p><ul><li>Node</li><li>Docker</li><li>Vscode</li><li>Postman</li></ul><p><strong>Project Structure</strong></p><p>clone repository: <a href="https://github.com/mrtripop/lambda-function-demo.git">https://github.com/mrtripop/lambda-function-demo.git</a></p><pre>node_modules<br>Dockerfile<br>handler.js<br>package-lock.json<br>package.json<br>test.js</pre><p><strong>Setup Project</strong></p><ol><li>Create sample directory</li></ol><pre>mkdir lambda-function-demo &amp;&amp; cd lambda-function-demo</pre><p>2. Initial package.json in order to install any dependency. If you want to use any service of AWS, install aws-sdk dependency and implement it in handler function.</p><pre>npm init -y &amp;&amp; npm install aws-sdk</pre><p>3. Create function handler file and poaste this code to handler.js file</p><pre>touch handler.js</pre><pre>exports.handler = async function (event) {<br>    return event.something;<br>};</pre><p>Now you will have these file in directory, these three file is already to handle request. Next step is about is testing without</p><pre>node_modules<br>handler.js<br>package-lock.json<br>package.json</pre><p>4. Create file for testing handler and paste this code to test.js file</p><pre>touch test.js</pre><pre>const lambda = require(&#39;./handler&#39;);<br><br>const simpleEvent = {<br> something: &#39;hello world&#39;,<br>};<br><br>const result = lambda.handler(simpleEvent);<br>console.log(&#39;result : &#39;, result);</pre><p>5. Testing using node</p><pre>node test.js</pre><p>Result will look like this</p><pre>result :  Promise { &#39;hello world&#39; }</pre><p>This is simple application that you can handle any request that come to Lambda. Next step we will use docker to simulation when we deploy on AWS Lambda function.</p><ol><li>Create docker file</li></ol><pre>touch Dockerfile</pre><p>2. Pasts this code in docker file. For any base image version, please checkout <a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-image.html">official document</a></p><pre>FROM public.ecr.aws/lambda/nodejs:18<br># Copy function code<br>COPY package.json ${LAMBDA_TASK_ROOT}/package.json<br>COPY handler.js ${LAMBDA_TASK_ROOT}/handler.js<br>WORKDIR ${LAMBDA_TASK_ROOT}<br>RUN npm install<br># Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)<br>CMD [ &quot;handler.handler&quot; ]</pre><p>3. Build docker image</p><pre>docker build -t lambda-demo-test .</pre><p>4. Run docker container with lambda-demo-testimage</p><pre>docker run --rm -p 9000:8080 --name lambda lambda-demo-test</pre><p>After run container, you will see log message like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfPOrZ5UbJx2CGWOgg92CQ.png" /></figure><p>This mean handler function can run without any issue. Then, make request to our handler function. You can use curl or Postman to make request with POST method.</p><p><strong>Request body</strong></p><pre>{<br>  &quot;something&quot;: &quot;Hello, something&quot;<br>}</pre><p><strong>Make request using </strong>curl</p><pre>curl -X POST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; -d &#39;{ &quot;something&quot; : &quot;Hello, something&quot; }&#39;</pre><p>response will return like this</p><pre>&quot;Hello, something&quot;%</pre><p><strong>Make request using </strong>Postman , you can import this json to your Postman</p><pre>{<br> &quot;info&quot;: {<br>  &quot;_postman_id&quot;: &quot;220d7a65-2e31-464c-bd0d-06e2df055595&quot;,<br>  &quot;name&quot;: &quot;aws-lambda-function&quot;,<br>  &quot;schema&quot;: &quot;https://schema.getpostman.com/json/collection/v2.1.0/collection.json&quot;,<br>  &quot;_exporter_id&quot;: &quot;21144856&quot;<br> },<br> &quot;item&quot;: [<br>  {<br>   &quot;name&quot;: &quot;lambda-demo-test&quot;,<br>   &quot;request&quot;: {<br>    &quot;method&quot;: &quot;POST&quot;,<br>    &quot;header&quot;: [],<br>    &quot;body&quot;: {<br>     &quot;mode&quot;: &quot;raw&quot;,<br>     &quot;raw&quot;: &quot;{\n    \&quot;something\&quot;: \&quot;Hello, something\&quot;\n}&quot;,<br>     &quot;options&quot;: {<br>      &quot;raw&quot;: {<br>       &quot;language&quot;: &quot;json&quot;<br>      }<br>     }<br>    },<br>    &quot;url&quot;: {<br>     &quot;raw&quot;: &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot;,<br>     &quot;protocol&quot;: &quot;http&quot;,<br>     &quot;host&quot;: [<br>      &quot;localhost&quot;<br>     ],<br>     &quot;port&quot;: &quot;9000&quot;,<br>     &quot;path&quot;: [<br>      &quot;2015-03-31&quot;,<br>      &quot;functions&quot;,<br>      &quot;function&quot;,<br>      &quot;invocations&quot;<br>     ]<br>    }<br>   },<br>   &quot;response&quot;: []<br>  }<br> ]<br>}</pre><p>After import this json, you will see aws-lambda-function collection in your workspace. In this collection will have request name lambda-demo-test . you can make request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*vFTlNSK5KWT7ec5DYXTleQ.png" /></figure><p>This is result from our handler function that run on docker container. You can push this docker image to AWS ECR and pull it to AWS Lambda Function for test you handler function on cloud.</p><p>In the end of this tutorial, I just show how to implement and setting up AWS Lambda project on local machine instead of implement on Lambda Console. You can read more detail in official document.</p><p>Hope you like, thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe983be1a08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro AWS Lambda ให้เข้าใจง่ายๆกัน]]></title>
            <link>https://medium.com/@mrtripop/intro-aws-lambda-%E0%B9%83%E0%B8%AB%E0%B9%89%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B9%83%E0%B8%88%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86%E0%B8%81%E0%B8%B1%E0%B8%99-5d58b723cfd?source=rss-2341d7a8ba4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d58b723cfd</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Tripop Torcheep]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 18:24:58 GMT</pubDate>
            <atom:updated>2023-01-23T18:24:58.804Z</atom:updated>
            <content:encoded><![CDATA[<p>สวัสดีท่านผู้อ่านทุกท่านนะครับ วันนี้เราจะมาคุยกันเกี่ยวกับ AWS Lambda ว่ามันคืออะไร ทำงานยังไง และสิ่งที่ควรระวังคืออะไร</p><p>เดาว่าหลายๆคนคงเคยได้ยินเกี่ยวกับ Serverless กันมาบ้าง Lambda ก็เป็นหนึ่งในนั้น วันนี้เราเลยจะมาอธิบายกันซักหน่อย ซึ่ง Implement จะเป็น part ถัดไป</p><h3>AWS Lambda คืออะไร</h3><p>AWS Lambda เป็นหนึ่งใน Function as a Service(FaaS) ที่ช่วยให้เราสามารถรันโค้ดได้ โดยไม่ต้องมีการเตรียมการหรือจัดการ Server แต่อย่างใด โดยทาง Lambda จะจัดการให้ทั้งหมด</p><p>สมมุติว่าเราพัฒนา Service ขึ้นมาแล้วนำไปรันบน Lambda เราสามารถเซ็ตการทำงานของ Lambda ให้เป็นเหมือน API เพื่อเรียกใช้ก็สามารถทำได้ แล้วถ้าเกิดว่า Lambda มี request เข้ามาเยอะมากๆ จน Instance ทำงานไม่ทันมันจะ Auto scale ให้โดยอัตโนมัติ ทำให้เราไม่ต้องมีปวดหัวเรื่องการจัดการปัญหาต่างๆ</p><p>อยากรู้จักลองทำตามได้ที่นี่เลย: <a href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html">https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html</a></p><h3>Workflow</h3><p>การทำงานของ Lambda ที่จะพูดถึงนี้จะถูกเซ็ตให้ทำงานในรูปแบบของ API ดังนั้นจะต้องมีทำงานร่วมกับ API Gateway โดยจะมีการส่ง Request เข้าไปที่ Lambda แล้วเกิดเป็น Workflow ตามภาพด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*xPLXIoOxrA4lDtWzpMUzAg.png" /><figcaption>อธิบายการทำงานร่วมกันระหว่าง API Gateway กับ Lambda</figcaption></figure><p>สิ่งที่ต้องรู้จักก่อนเลยคือ Lambda + Function ซึ่ง Function จะทำงานอยู่ใน Execution Environment เมื่อเกิดการ Invoke เกิดขึ้นและ Lambda Service จะคอยควบคุมการทำงานของ Function และเมื่อได้ผลลัพธ์ Lambda ก็จะส่งต่อไปให้ API Gateway เพื่อ response กลับไปให้ Client นั่นเองครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bpBZlsHDQqhjj_05.png" /><figcaption>อ้างอิงจาก AWS Lambda Developer Guide</figcaption></figure><p>เวลาสร้างฟังก์ชันขึ้นมา ที่ Lambda Console จะพบค่าเริ่มต้นของ Memory, Time limit และอื่นๆ ซึ่ง Lambda จะใช้ค่าต่างๆเหล่านี้ในการ setup Execution Environment</p><p>หลังจาก setup แล้ว Execution Environment จะคอยจัดการ resource ที่ต้องใช้ในการรัน Function ซึ่งรวมถึง Runtime, Extensions และ Telemetry ต่างๆครับ</p><p>ดังนั้นหัวข้อถัดไป ผมจะพาลงลึงกับ Execution environment lifecycle กันก่อนนะครับ ทุกคนจะได้รู้จักนิสัยของ Lambda กัน เพราะผมเคย Implement เจ้า Lambda นี้โดยไม่รู้เชิงลึก จึงเกิดเป็นปัญหาตามมาครับ</p><h3>วงจรชีวิตของ Execution Environment</h3><p>Execution environment จะมีการทำงานอยู่ทั้งหมด 4 phase แบ่งเป็น</p><ul><li>Init phase</li><li>Restore phase</li><li>Invoke phase</li><li>Shutdown phase</li></ul><p>แต่ละ phase จะเริ่มต้นด้วย event ที่ Lambda ส่งเข้ามาให้ runtime และ extension โดยเมื่อทำ phase นั้นๆเสร็จสิ้นแล้ว runtime และ extension จะส่ง Next API request ออกมาเพื่อบอก Lambda ว่า phase ต่อไปคืออะไร</p><p>หลังจากเสร็จสิ้นทุก phase แล้ว Lambda จะ freeze execution environment ถ้าไม่มี event มารอประมวลผล ก็คือไม่ได้เคลียร์ execution environment ทิ้งทันที แต่จะเก็บไว้เป็นระยะเวลานึงก่อน ถ้ายังไม่มี event เข้ามาค่อยเคลียร์</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z91duK8v4_0YCKAd.png" /><figcaption>อ้างอิงจาก Lambda execution environment</figcaption></figure><h4>Init Phase</h4><p>Init phase จะมี task อยู่ 3 อย่างหลักๆ</p><ol><li>Extensions init</li><li>Runtime init</li><li>Function init (run function’s static code)</li></ol><p>โดยการทำทั้ง 3 task จะถูก limit ไว้ที่ 10 วินาที ถ้าทำไม่เสร็จภายใน 10 วินาที Lambda จะพยายามทำ Init phase อีกครั้ง ในการ invocation แรกที่มีการเรียก Function เมื่อทำการ Init เสร็จแล้วก็จะเข้าสู่ Invoke phase</p><p>ถ้าเรา Deploy Function ในรูปแบบของการ publish version เราจะสามารถทำ SnapStart ได้ ซึ่งข้อดีคือ Lambda จะทำการ snapshot และ cache ไว้ทำให้รันครั้งถัดไปเร็วขึ้น</p><h4>Restore Phase(SnapStart only)</h4><p>ถ้าเราไม่ได้ Invoke Function นานๆหรือ Function มีการ scale up เช่น เมื่อมี request เข้ามาเยอะมากๆ Lambda จะ initial จาก SnapStart แทนที่จะต้อง initial จากจุดศูนย์ และเมื่อ Restore phase ทำเสร็จสิ้นก็จะเข้าสู่ Invoke Phase</p><h4>Invoke Phase</h4><p>Timeout duration ที่เราตั้งค่าที่ Lambda Console จะถูกนับแค่ใน phase นี้เท่านั้น เช่นถ้าเรา set timeout ไว้ 1 นาที function และ extension ต้องประมวลผลให้เสร็จภายใน 1 นาที</p><p>ถ้า function เกิด crashe หรือ timeout เกิดขึ้น Lambda จะทำการ reset execution environment หรือก็คือ Shutdown phase</p><h4>Shutdown Phase</h4><p>Lambda จะเริ่มจากการ shutdown runtime ก่อน หลังจากนั้นก็จะส่ง shutdown event ออกมาให้ external extension ซึ่งก็รวมถึง log ที่บอกว่า function timeout</p><p>ซึ่ง shutdown phase ถูกกำหนดไว้ให้ทำให้เสร็จภายใน 2 วินาที ซึ่งถ้าไม่ทัน Lambda จะทำการ terminate ทิ้งด้วยสัญญาณ SIGKILL</p><p>หลังจากนั้น Lambda จะ freeze execution environment ไว้ เมื่อมี invocation เข้ามาใหม่ execution environment จะถูกใช้อีกครั้ง</p><h3>สิ่งที่ควรระวังในการใช้งาน</h3><ul><li>Code ภายนอก function handler ควรมีแต่ static เช่น ค่าคงที่, environment variable ต่างๆ หรือการประกาศ function เพราะถ้ามีการ initial ข้างนอก function handler อาจทำให้เกิด error ที่ init phase ได้</li><li>Cost จะเพิ่มตาม duration ที่ใช้ในการรัน code ดังนั้น function ที่เหมาะกับ lambda ไม่ควรเป็น function ที่ใช้เวลาเยอะ ถ้ามี request เยอะด้วย</li><li>Timeout duration ควรตั้งเผื่อไว้ซักเล็กน้อย ไม่ควรตั้งพอดีจนเกินไป</li><li>ปรับ Memory ให้เหมาะสมกับการใช้งานของ function</li></ul><p>อ่านมาถึงตรงนี้ก็หวังว่าจะเข้าใจการทำของ AWS Lambda มากขึ้นนะครับ ทั้งถ้าหากมีข้อผิดพลาดประการใดขออภัยมา ณ ที่นี้นะครับ</p><h3>Reference:</h3><ul><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html">https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">https://docs.aws.amazon.com/lambda/latest/dg/welcome.html</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html">https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-foundation.html">https://docs.aws.amazon.com/lambda/latest/dg/lambda-foundation.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d58b723cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>