⛶ bấm để phóng to
Mạng máy tính chia việc thành nhiều tầng. Mỗi tầng lo đúng một nhiệm vụ. Khi ứng dụng tạo một request, dữ liệu đi xuống chồng tầng theo thứ tự. Mỗi tầng gắn thêm một header của riêng nó vào trước dữ liệu. Cơ chế này tên là encapsulation.
Tầng vận chuyển gắn số cổng. Tầng mạng gắn địa chỉ IP để định tuyến. Tầng liên kết gắn địa chỉ MAC của chặng kế tiếp. Máy nhận bóc các header theo chiều ngược lại để lấy lại dữ liệu gốc.
A computer network splits the work into layers. Each layer handles one job. When an app creates a request, the data travels down the stack. Each layer prepends its own header to the data. This mechanism is called encapsulation.
The transport layer adds port numbers. The network layer adds the IP address for routing. The link layer adds the next-hop MAC address. The receiver strips off the headers in reverse order to recover the original data.
⛶ bấm để phóng to
Tầng vận chuyển có hai giao thức. TCP là giao thức tin cậy. Trước khi truyền, hai bên thực hiện three-way handshake để thiết lập kết nối.
TCP đánh số từng byte. Bên nhận báo nhận từng đoạn. Đoạn nào thất lạc, TCP tự gửi lại. Dữ liệu đến đầy đủ và đúng thứ tự. Cái giá là độ trễ cao hơn và nhiều chi phí điều khiển hơn. Web, API, chuyển khoản và tải file đều chạy trên TCP, vì chúng không chấp nhận mất dữ liệu.
The transport layer has two protocols. TCP is the reliable one. Before sending, both sides perform a three-way handshake to establish a connection.
TCP numbers every byte. The receiver acknowledges each segment. Any lost segment is retransmitted. Data arrives complete and in order. The cost is higher latency and more control overhead. Web, APIs, payments and file transfers all run on TCP, because they cannot tolerate data loss.
⛶ bấm để phóng to
Giao thức thứ hai là UDP. UDP gửi dữ liệu đi ngay. Nó không thiết lập kết nối, không báo nhận, không gửi lại. UDP nhanh và có độ trễ rất thấp. Cái giá là dữ liệu có thể mất hoặc sai thứ tự.
Chọn UDP khi dữ liệu đến trễ là vô dụng. Gọi video, game thời gian thực và DNS đều dùng UDP. Một khung hình video đến muộn không còn giá trị, nên bỏ qua nó tốt hơn chờ gửi lại. HTTP/3 cũng chuyển sang UDP vì lý do này.
The second protocol is UDP. UDP sends data immediately. It sets up no connection, sends no acknowledgements, and never retransmits. UDP is fast and has very low latency. The cost is that data may be lost or arrive out of order.
Choose UDP when late data is useless. Video calls, real-time games and DNS all use UDP. A late video frame has no value, so dropping it beats waiting for a resend. HTTP/3 also moved to UDP for this reason.
⛶ bấm để phóng to
HTTP là giao thức request–response. Client gửi request, server trả response. Điểm khác biệt giữa các phiên bản nằm ở cách xử lý nhiều request cùng lúc trên một kết nối.
HTTP/1.1 xử lý request tuần tự trên mỗi kết nối. Request sau phải đợi response của request trước. Một response chậm làm nghẽn cả hàng phía sau. Hiện tượng này tên là head-of-line blocking. Trình duyệt giảm tác động bằng cách mở tới 6 kết nối song song cho mỗi tên miền.
HTTP is a request–response protocol. The client sends a request, the server returns a response. The difference between versions lies in how they handle many requests at once on one connection.
HTTP/1.1 processes requests sequentially on each connection. A later request must wait for the earlier response. One slow response blocks the queue behind it. This is called head-of-line blocking. Browsers mitigate this by opening up to 6 parallel connections per domain.
⛶ bấm để phóng to
HTTP/2 dùng multiplexing. Nhiều luồng chạy đồng thời trên một kết nối, kèm nén header. Điều này xóa head-of-line blocking ở tầng HTTP. Ở tầng TCP, vấn đề vẫn còn: TCP đảm bảo thứ tự cho cả kết nối, nên một gói TCP mất làm mọi luồng dừng chờ.
HTTP/3 chạy trên QUIC, một giao thức dựng trên UDP. Mỗi luồng trong QUIC độc lập. Mất gói ở một luồng không ảnh hưởng luồng khác. QUIC gộp luôn bước mã hóa vào lúc thiết lập kết nối, giảm số vòng bắt tay. HTTP/3 chạy mượt hơn trên mạng di động hay rớt gói.
HTTP/2 uses multiplexing. Many streams run concurrently on one connection, with header compression. This removes head-of-line blocking at the HTTP layer. At the TCP layer the problem persists: TCP guarantees order for the whole connection, so one lost TCP packet stalls every stream.
HTTP/3 runs on QUIC, a protocol built on UDP. Each QUIC stream is independent. A lost packet on one stream does not affect the others. QUIC also folds encryption into connection setup, cutting handshake round-trips. HTTP/3 runs smoother on flaky mobile networks.
⛶ bấm để phóng to
HTTP cổ điển để client hỏi trước. Khi cần server chủ động đẩy dữ liệu, có ba mức giải pháp. Polling: client hỏi lại theo chu kỳ, tạo nhiều request rỗng. Long-polling: server giữ request tới khi có dữ liệu mới. SSE: một kênh một chiều server đẩy xuống client, bền vững, hợp cho thông báo và feed.
WebSocket mở một kênh hai chiều luôn mở giữa client và server. Nó hợp cho chat và cộng tác thời gian thực. Mỗi client giữ một kết nối liên tục, nên WebSocket khó cân bằng tải và mở rộng hơn. Quy tắc chọn: dùng SSE cho nhu cầu một chiều, dùng WebSocket khi bắt buộc hai chiều.
Classic HTTP lets the client ask first. When the server must push data on its own, there are three levels. Polling: the client asks again periodically, creating many empty requests. Long-polling: the server holds the request until new data appears. SSE: a one-way channel where the server pushes to the client, persistent, good for notifications and feeds.
WebSocket opens a two-way channel that stays open between client and server. It suits chat and real-time collaboration. Each client holds a persistent connection, so WebSocket is harder to load-balance and scale. The rule: use SSE for one-way needs, use WebSocket when two-way is mandatory.
⛶ bấm để phóng to
HTTPS là HTTP chạy bên trong đường hầm mã hóa TLS. Trước khi truyền dữ liệu, hai bên thực hiện một handshake để dựng đường hầm. Handshake làm hai việc. Việc thứ nhất là xác thực server.
Server trình ra một certificate chứa public key của nó. Certificate được một Certificate Authority ký. Trình duyệt kiểm tra chữ ký của CA để xác nhận public key thuộc đúng server đó. Kẻ tấn công không thể giả ra một certificate có chữ ký CA hợp lệ.
HTTPS is HTTP running inside the TLS encryption tunnel. Before sending data, both sides perform a handshake to build the tunnel. The handshake does two things. The first is authenticating the server.
The server presents a certificate containing its public key. The certificate is signed by a Certificate Authority. The browser checks the CA signature to confirm the public key belongs to that exact server. An attacker cannot forge a certificate with a valid CA signature.
⛶ bấm để phóng to
Việc thứ hai của handshake là thỏa thuận một session key bí mật. Hai bên dùng cơ chế khóa công khai để cùng tạo ra khóa này. Toàn bộ dữ liệu sau đó được mã hóa bằng session key.
Handshake tốn round-trip. Mỗi round-trip cộng thêm độ trễ. Khi server ở xa, chi phí này lớn. TLS 1.2 cần hai vòng. TLS 1.3 cần một vòng, và hỗ trợ 0-RTT khi nối lại phiên cũ. Bật TLS 1.3 và session resumption là một quyết định hiệu năng cụ thể.
The handshake's second job is to agree on a secret session key. Both sides use public-key cryptography to derive this key together. All later data is encrypted with the session key.
The handshake costs round-trips. Each round-trip adds latency. When the server is far away, this cost is large. TLS 1.2 needs two round-trips. TLS 1.3 needs one, and supports 0-RTT when resuming an old session. Enabling TLS 1.3 and session resumption is a concrete performance decision.
⛶ bấm để phóng to
Có hai loại mã hóa. Mã hóa đối xứng dùng một khóa chung cho cả mã hóa và giải mã. Nó nhanh và nhẹ.
Đối xứng có một điểm yếu cốt lõi. Hai bên phải có cùng khóa trước khi nói chuyện. Trao khóa qua mạng thì kẻ nghe lén bắt được. Khi có khóa, kẻ nghe lén giải mã được mọi thứ. Đây là bài toán phân phối khóa. Đối xứng một mình không đủ để bảo mật trên Internet.
There are two kinds of encryption. Symmetric encryption uses one shared key for both encryption and decryption. It is fast and lightweight.
Symmetric encryption has a core weakness. Both sides must hold the same key before they talk. Sending the key over the network lets an eavesdropper capture it. Once they have the key, they decrypt everything. This is the key distribution problem. Symmetric encryption alone is not enough to secure the Internet.
⛶ bấm để phóng to
Mã hóa bất đối xứng dùng một cặp khóa: public key công khai và private key giữ kín. Thứ mã hóa bằng public key chỉ private key mở được. Nhờ vậy không cần trao khóa bí mật qua mạng. Bất đối xứng chậm hơn đối xứng hàng trăm tới hàng nghìn lần.
TLS kết hợp cả hai theo mô hình lai. Bất đối xứng làm đúng một việc: trao đổi an toàn một khóa đối xứng phiên. Sau đó toàn bộ dữ liệu được mã hóa bằng đối xứng. Mô hình này giải bài toán phân phối khóa. Nó cũng giữ được tốc độ. Gần như mọi giao thức bảo mật hiện đại đều dựng trên cách phân vai này.
Asymmetric encryption uses a key pair: a public public key and a private private key. What the public key locks, only the matching private key unlocks. So no secret key needs to cross the network. Asymmetric encryption is hundreds to thousands of times slower than symmetric.
TLS combines both in a hybrid model. Asymmetric does one job: securely exchanging a symmetric session key. After that, all data is encrypted with symmetric. This model solves the key distribution problem. It also keeps the speed. Almost every modern security protocol is built on this division of roles.
⛶ bấm để phóng to
HTTP có nhiều verb. Hai tính chất quyết định cách dùng chúng. Safe nghĩa là verb không thay đổi trạng thái server. Nó chỉ đọc. GET là verb safe.
Idempotent nghĩa là gọi một lần hay nhiều lần cho cùng kết quả trên server. GET, PUT và DELETE đều idempotent. PUT thay toàn bộ tài nguyên, nên gửi lại cùng nội dung không tạo ra gì mới. DELETE một thứ đã xóa vẫn cho trạng thái đã xóa. POST tạo tài nguyên mới, nên không idempotent. PATCH sửa một phần, thường cũng không idempotent.
HTTP has several verbs. Two properties decide how you use them. Safe means the verb does not change server state. It only reads. GET is a safe verb.
Idempotent means calling once or many times gives the same server result. GET, PUT and DELETE are idempotent. PUT replaces the whole resource, so resending the same body creates nothing new. DELETE on an already-deleted item still leaves it deleted. POST creates a new resource, so it is not idempotent. PATCH does a partial update and is usually not idempotent either.
⛶ bấm để phóng to
Tính idempotent quan trọng vì mạng chập chờn. Client thường retry khi không nhận được phản hồi. Với verb idempotent, retry vô hại. Với POST, một lần retry có thể tạo hai đơn hàng và trừ tiền hai lần.
Lời giải công nghiệp là idempotency key. Client sinh một khóa duy nhất cho mỗi thao tác và gắn vào header. Server lưu kết quả theo khóa đó. Request đến với khóa đã thấy thì server trả kết quả cũ, không thực thi lại. Stripe và phần lớn cổng thanh toán dùng đúng cơ chế này.
Idempotency matters because networks are unreliable. A client often retries when it gets no response. With an idempotent verb, a retry is harmless. With POST, one retry can create two orders and charge twice.
The industry fix is an idempotency key. The client generates a unique key per operation and puts it in a header. The server stores the result keyed by that value. A request with a seen key gets the stored result instead of running again. Stripe and most payment gateways rely on this exact mechanism.
⛶ bấm để phóng to
Status code chia theo chữ số đầu. 2xx là thành công. 3xx là chuyển hướng. 4xx là lỗi phía client. 5xx là lỗi phía server. Nắm nhóm là đủ cho phần lớn tình huống.
Hai cặp dễ nhầm hay bị hỏi. 401 nghĩa là chưa xác thực, hãy đăng nhập. 403 nghĩa là đã biết anh là ai và anh không có quyền. 301 là chuyển vĩnh viễn, trình duyệt cache lại và công cụ tìm kiếm đổi link. 302 là chuyển tạm thời.
Status codes are grouped by their first digit. 2xx is success. 3xx is redirection. 4xx is a client error. 5xx is a server error. Knowing the classes covers most cases.
Two confusing pairs come up often. 401 means not authenticated; please log in. 403 means we know who you are and you lack permission. 301 is a permanent redirect; the browser caches it and search engines move the link. 302 is a temporary redirect.
⛶ bấm để phóng to
Khi production trả lỗi server, ba mã 5xx chỉ đúng tầng nào hỏng. 502 Bad Gateway nghĩa là reverse proxy nhận phản hồi hỏng từ dịch vụ phía sau. Thường là upstream crash hoặc trả rác.
503 Service Unavailable nghĩa là dịch vụ tạm thời không phục vụ được, do quá tải hoặc đang bảo trì. 504 Gateway Timeout nghĩa là proxy chờ upstream quá lâu mà không có phản hồi. Đọc đúng ba mã này giúp khoanh nhanh nguyên nhân: 502 nghiêng về lỗi ứng dụng, 503 về năng lực, 504 về độ trễ.
When production returns server errors, three 5xx codes point to the failing layer. 502 Bad Gateway means the reverse proxy got a bad response from a service behind it. The upstream crashed or returned garbage.
503 Service Unavailable means the service is temporarily down, from overload or maintenance. 504 Gateway Timeout means the proxy waited too long for the upstream. Reading these three correctly narrows down the cause fast: 502 points to app errors, 503 to capacity, 504 to latency.
⛶ bấm để phóng to
Header gói nhiều cơ chế ngầm của web. Phần đáng giá nhất là caching, và có hai chiến lược. Cache-Control: max-age bảo trình duyệt và CDN giữ bản sao trong N giây mà không hỏi lại. Cách này nhanh nhất. Cái giá là có thể phục vụ dữ liệu cũ trong N giây đó.
ETag là vân tay nội dung. Client gửi kèm If-None-Match. Nếu nội dung chưa đổi, server trả 304 Not Modified với thân rỗng. Cách này luôn chính xác. Cái giá là tốn một round-trip để hỏi.
Headers carry many of the web's hidden mechanics. The most valuable part is caching, and there are two strategies. Cache-Control: max-age tells the browser and CDN to keep a copy for N seconds without asking again. This is the fastest path. The cost is serving stale data during those N seconds.
ETag is a content fingerprint. The client sends If-None-Match. If the content is unchanged, the server returns 304 Not Modified with an empty body. This is always accurate. The cost is one round-trip to ask.
⛶ bấm để phóng to
Tài nguyên tĩnh dùng kỹ thuật cache-busting. Đặt hash nội dung vào tên file và cho max-age rất dài kèm immutable. Khi nội dung đổi, tên file đổi theo, nên trình duyệt tải bản mới mà không cần hỏi.
CORS giải thích vì sao frontend ở domain này gọi API ở domain khác bị chặn. Trình duyệt chặn theo mặc định. Server phải trả header Access-Control-Allow-Origin để cho phép. Đây là cơ chế bảo vệ của trình duyệt, không phải lỗi backend.
Static assets use a cache-busting technique. Put a content hash in the file name and set a very long max-age with immutable. When the content changes, the file name changes, so the browser fetches the new version without asking.
CORS explains why a frontend on one domain calling an API on another gets blocked. The browser blocks it by default. The server must return the Access-Control-Allow-Origin header to allow it. This is a browser safeguard, not a backend bug.
⛶ bấm để phóng to
URI là khái niệm bao trùm. Nó là bất cứ chuỗi nào định danh một tài nguyên. URL và URN là hai loại URI.
URL định vị tài nguyên bằng địa chỉ và cách truy cập, gồm giao thức, host và đường dẫn. URN định danh bằng tên bền vững, độc lập vị trí. Một mã ISBN sách là URN. Thực tế ta gặp URL gần như mọi lúc.
URI is the umbrella term. It is any string that identifies a resource. URL and URN are two kinds of URI.
URL locates a resource by its address and access method: scheme, host and path. URN identifies by a persistent name, independent of location. A book's ISBN is a URN. In practice we meet URLs almost everywhere.
⛶ bấm để phóng to
Một URL gồm: scheme (https), host và port, path, query sau dấu hỏi, và fragment sau dấu thăng. Path định danh tài nguyên theo phân cấp. Query dùng để lọc, sắp xếp và phân trang.
Một chi tiết hay bị hỏi: fragment không bao giờ được gửi lên server. Trình duyệt giữ nó ở client. Tính chất này là nền tảng của client-side routing trong các single-page app đời đầu.
A URL has: the scheme (https), host and port, path, query after the question mark, and fragment after the hash. The path identifies a resource hierarchically. The query is for filtering, sorting and pagination.
One detail that gets asked: the fragment is never sent to the server. The browser keeps it on the client. This property underpins client-side routing in early single-page apps.
⛶ bấm để phóng to
Web không nhớ gì giữa các request. Ta cần cơ chế để server biết anh là ai qua nhiều lần gọi. Cách thứ nhất là session. Sau khi đăng nhập, server tạo một bản ghi trạng thái và lưu ở phía mình. Nó gửi cho client một session-id cất trong cookie.
Mỗi request sau, client đưa session-id. Server tra ngược ra danh tính. Đây là mô hình stateful. Xóa bản ghi là người dùng bị đăng xuất ngay. Payload gửi đi rất nhỏ.
The web remembers nothing between requests. We need a way for the server to know who you are across calls. The first way is a session. After login, the server creates a state record and stores it on its side. It sends the client a session-id kept in a cookie.
On each later request, the client presents the session-id. The server looks up the identity. This is the stateful model. Deleting the record logs the user out instantly. The payload sent is very small.
⛶ bấm để phóng to
Cách thứ hai là token. Server ký một JWT chứa sẵn thông tin người dùng và gửi cho client. Mỗi request client mang token. Server chỉ kiểm tra chữ ký là tin được, không cần tra kho. Đây là mô hình stateless. Nó scale rất đẹp cho microservices, vì mỗi service tự verify.
JWT có một điểm yếu. Token đã ký còn hiệu lực tới khi hết hạn, dù người dùng đã logout. Thu hồi trước hạn khó. Lời giải thực chiến là TTL ngắn, kèm refresh token và một danh sách thu hồi nhỏ.
The second way is a token. The server signs a JWT that already holds the user info and sends it to the client. On each request the client carries the token. The server just verifies the signature, with no store to query. This is the stateless model. It scales beautifully for microservices, since each service verifies on its own.
JWT has one weakness. A signed token stays valid until it expires, even after the user logs out. Early revocation is hard. The practical fix is a short TTL, plus a refresh token and a small denylist.
⛶ bấm để phóng to
Cả hai đều là trung gian. Khác nhau ở chỗ đứng về phía ai. Forward proxy đứng trước client và đại diện cho client. Mọi request của client đi qua nó trước khi ra Internet. Nó dùng để ẩn danh người dùng, lọc nội dung và vượt chặn. Server bên kia chỉ thấy proxy.
Reverse proxy đứng trước server và đại diện cho server. Mọi request từ Internet đi qua nó trước khi tới backend. Client chỉ thấy reverse proxy, không thấy các máy chủ thật phía sau.
Both are intermediaries. They differ in whose side they sit on. A forward proxy sits in front of the client and acts on behalf of the client. Every client request goes through it before reaching the Internet. It is used to anonymize users, filter content and bypass blocks. The far server sees only the proxy.
A reverse proxy sits in front of the server and acts on behalf of the server. Every request from the Internet passes through it before reaching the backend. The client sees only the reverse proxy, not the real machines behind it.
⛶ bấm để phóng to
Reverse proxy là nhân vật quen thuộc trong system design vì nó gánh nhiều việc nặng. Nó cân bằng tải giữa nhiều backend. Nó giải mã TLS tại một chỗ để backend khỏi lo mã hóa. Nó cache nội dung tĩnh. Nó chặn tấn công bằng rate limit và WAF.
Cái giá là thêm một hop trên đường đi và một thành phần phải làm high-availability. Đổi lại, mọi mối quan tâm xuyên suốt gom về một nơi. Nginx, Envoy và Cloudflare đều là reverse proxy.
The reverse proxy is a familiar figure in system design because it carries heavy work. It load-balances across backends. It terminates TLS in one place so backends skip encryption. It caches static content. It blocks attacks with rate limiting and a WAF.
The cost is one extra hop and a component that must be highly available. In return, every cross-cutting concern is gathered in one place. Nginx, Envoy and Cloudflare are all reverse proxies.
⛶ bấm để phóng to
API Gateway là một reverse proxy được nâng cấp, đặt trước cả một hệ microservices. Thay vì để mỗi service tự lo những việc giống nhau, gateway gom chúng về một điểm vào.
Gateway xử lý xác thực và phân quyền, rate limiting, định tuyến tới đúng service, gộp nhiều lời gọi thành một, ghi log và metrics, và chuyển đổi giao thức. Các service phía sau nhờ vậy gọn nhẹ, chỉ lo nghiệp vụ. Client chỉ cần biết một địa chỉ.
An API Gateway is an upgraded reverse proxy placed in front of a whole microservices system. Instead of letting each service redo the same work, the gateway centralizes it at one entry point.
The gateway handles authentication and authorization, rate limiting, routing to the right service, aggregating several calls into one, logging and metrics, and protocol translation. The services behind it stay lean and focus on business logic. The client only needs one address.
⛶ bấm để phóng to
Tập trung mang lại hai rủi ro. Thứ nhất, gateway dễ thành single point of failure và một nút thắt hiệu năng. Mọi traffic đi qua nó, nên nó phải làm high-availability và scale cẩn thận.
Thứ hai, có cám dỗ nhồi business logic vào gateway. Làm vậy biến nó thành một khối khổng lồ khó bảo trì. Nguyên tắc lành mạnh là giữ gateway mỏng. Nó chỉ xử lý mối quan tâm xuyên suốt. Nghiệp vụ để nguyên trong service.
Centralizing brings two risks. First, the gateway easily becomes a single point of failure and a performance bottleneck. All traffic passes through it, so it must be highly available and scaled carefully.
Second, there is a temptation to push business logic into the gateway. That turns it into a giant, hard-to-maintain block. The healthy rule is to keep the gateway thin. It only handles cross-cutting concerns. Business logic stays inside the services.
⛶ bấm để phóng to
Khi người dùng rải khắp thế giới, việc gửi họ tới đúng endpoint là một quyết định kiến trúc. Nó thường được thực hiện ngay ở tầng DNS, ví dụ Route 53, trước khi request chạm server.
Có vài chính sách. Latency-based gửi user tới region nhanh nhất. Geolocation định tuyến theo vị trí địa lý, quan trọng cho tuân thủ data residency. Weighted chia phần trăm traffic. Failover chuyển sang region dự phòng khi region chính chết.
When users are spread worldwide, sending them to the right endpoint is an architecture decision. It usually happens at the DNS layer, such as Route 53, before the request reaches a server.
There are several policies. Latency-based sends a user to the fastest region. Geolocation routes by geography, important for data residency compliance. Weighted splits a percentage of traffic. Failover switches to a backup region when the primary goes down.
⛶ bấm để phóng to
Weighted routing là công cụ cho canary deploy. Đẩy 5% người dùng sang phiên bản mới, theo dõi lỗi, rồi tăng dần. Nó cũng dùng để chạy A/B test.
Một câu hỏi kinh điển là thiết kế hệ phục vụ người dùng toàn cầu. Câu trả lời mạnh ghép nhiều mảnh: latency-based routing đưa user tới region gần nhất, CDN phục vụ nội dung tĩnh ở rìa mạng, kiến trúc multi-region để chịu lỗi, và weighted routing để tung phiên bản mới an toàn.
Weighted routing is the tool for a canary deploy. Push 5% of users to the new version, watch for errors, then ramp up. It also runs A/B tests.
A classic question is designing a system for global users. A strong answer composes several pieces: latency-based routing sends users to the nearest region, a CDN serves static content at the network edge, a multi-region architecture tolerates failure, and weighted routing rolls out new versions safely.
Topic 2 dạy cách các service nói chuyện với nhau: REST, GraphQL, gRPC, WebSocket, và khi nào chọn kiểu nào.