Git Objects: Blobs, Trees, Commits, Tags

Learn Git's four core object types, how commits reference trees, and how content-addressed storage works with SHA-1 and SHA-256 repositories.

published: reading time: 21 min read author: Geek Workbench updated: November 17, 2026
Quick Summary

Git has four core object types: blobs store file contents, trees name blobs and subtrees, commits reference root trees and parent commits, and tag objects annotate other objects. Object IDs use the repository's hash format. Commits represent logical snapshots, while unchanged objects can be reused and pack files can delta-compress similar content.

Introduction

Git uses a content-addressed object database. Its four core object types are blobs, trees, commits, and tag objects.

A commit records a root tree and its parent commit or commits, which gives Git a logical snapshot of the tracked paths at that point in history. The tree points to content-addressed blob and subtree objects. When content is unchanged, commits can reuse existing objects; Git does not copy every file’s contents into every commit. Pack files may also delta-compress similar objects on disk. The IDs linking objects use the repository’s hash format.

This article examines each object type in depth, shows how they interconnect, and teaches you to inspect them using Git’s plumbing commands. By the end, you’ll be able to manually reconstruct a Git repository from raw objects if needed.

When to Use / When Not to Use

When to understand Git objects:

  • Debugging corruption or missing data in repositories
  • Building Git tooling or integrations
  • Understanding how Git achieves integrity verification
  • Optimizing repository size and performance
  • Recovering lost data from the object database

When not to manipulate objects directly:

  • Daily development — use porcelain commands (git add, git commit)
  • When unsure — direct object manipulation can corrupt repositories
  • For simple history inspection — git log and git show are sufficient

Core Concepts

Git stores objects in an object database, often under .git/objects/; linked worktrees and alternates can use a different path. Each object ID is derived from the object’s type, length, and content. The four core object types are:


graph TD
    TAG["Annotated Tag\n(type: tag)"] -->|points to| COMMIT["Commit\n(type: commit)"]
    COMMIT -->|tree: points to| TREE["Tree\n(type: tree)"]
    COMMIT -->|parent: points to| COMMIT2["Parent Commit"]
    TREE -->|contains| TREE2["Subdirectory Tree"]
    TREE -->|contains| BLOB1["Blob\n(file content)"]
    TREE -->|contains| BLOB2["Blob\n(file content)"]
    TREE2 -->|contains| BLOB3["Blob\n(file content)"]

The relationship is hierarchical: tags point to commits, commits point to trees (and parent commits), trees point to other trees and blobs. Blobs are the leaves — they contain actual file content.

Each object is stored as:


<object type> <content length>\0<content>

This header is zlib-compressed and stored under a path derived from the object’s ID. The path length depends on the repository’s hash format.

Most repositories use SHA-1 by default. Git can also create SHA-256 repositories when enabled; SHA-1 object IDs have 40 hexadecimal characters and SHA-256 IDs have 64. Git’s current git init documentation says the two repository formats do not interoperate directly, so check client, server, and hosting support before choosing one. The examples below use the traditional SHA-1 format unless stated otherwise. For details, see Git’s hash-function transition documentation.

Architecture or Flow Diagram


flowchart LR
    FILE["File Content"] -->|git hash-object| BLOB["Blob Object\nobject ID: abc123..."]
    BLOB -->|referenced by| TREE["Tree Object\nobject ID: def456..."]
    TREE -->|referenced by| COMMIT["Commit Object\nobject ID: 789ghi..."]
    COMMIT -->|referenced by| TAG["Tag Object\nobject ID: jkl012..."]

    META["Author, Date, Message"] --> COMMIT
    PARENT["Parent object ID"] --> COMMIT

The flow shows how file content becomes a blob, which is referenced by a tree, which is referenced by a commit, which may be referenced by a tag. Metadata flows into commits separately from content.

Step-by-Step Guide / Deep Dive

Blob Objects

Blobs store file content. They do not store filenames, permissions, or directory structure — just raw bytes.


# Create a blob from a file
echo "Hello, Git!" | git hash-object -w --stdin
# Output: 8ab686eafeb1f44702738c8b0f24f2567c36da6d

# The object is now in .git/objects/8a/
ls .git/objects/8a/

# Inspect the blob
git cat-file -p 8ab686eafeb1f44702738c8b0f24f2567c36da6d
# Output: Hello, Git!

# Check the type
git cat-file -t 8ab686eafeb1f44702738c8b0f24f2567c36da6d
# Output: blob

Key properties:

  • Content-addressable: identical files produce identical blobs (deduplication)
  • Immutable: once created, a blob never changes
  • No metadata: filename and permissions are stored in the tree, not the blob

Tree Objects

Trees represent directories. They map filenames to blob object IDs (or tree object IDs for subdirectories).


# Create a tree from the current index
git write-tree
# Output: 4b825dc642cb6eb9a060e54bf899d69f824970a0

# Inspect a tree
git cat-file -p 4b825dc642cb6eb9a060e54bf899d69f824970a0
# Output format:
# 100644 blob abc123... file1.txt
# 040000 tree def456... subdir/
# 100755 blob 789ghi... script.sh

Each tree entry contains:

  • Mode: file permissions (100644 for regular files, 100755 for executables, 040000 for directories)
  • Type: blob or tree
  • Object ID: identifier of the referenced object, using the repository’s hash format
  • Filename: the name within this directory

Commit Objects

Commits are the backbone of Git history. Each commit records a snapshot (via a tree), authorship, and lineage.


# Create a commit object manually
export GIT_AUTHOR_NAME="Test User"
export GIT_AUTHOR_EMAIL="test@example.com"
export GIT_COMMITTER_NAME="Test User"
export GIT_COMMITTER_EMAIL="test@example.com"
export GIT_AUTHOR_DATE="2026-03-31T12:00:00+00:00"
export GIT_COMMITTER_DATE="2026-03-31T12:00:00+00:00"

TREE_SHA=$(git write-tree)
COMMIT_SHA=$(echo "Initial commit" | git commit-tree $TREE_SHA)

echo $COMMIT_SHA
# Output: a1b2c3d4e5f6...

# Inspect the commit
git cat-file -p $COMMIT_SHA
# Output:
# tree 4b825dc642cb6eb9a060e54bf899d69f824970a0
# author Test User <test@example.com> 1711886400 +0000
# committer Test User <test@example.com> 1711886400 +0000
#
# Initial commit

A commit object contains:

  • tree: object ID of the root tree (the snapshot)
  • parent: object ID of each parent commit — none for an initial commit, one for a normal commit, two or more for a merge
  • author: who wrote the code (name, email, timestamp, timezone)
  • committer: who committed the code (can differ from author, e.g., after rebase)
  • message: the commit message

Tag Objects

There are two types of tags in Git:

Lightweight tags are simply refs pointing to a commit — no tag object is created:


git tag v1.0-lightweight
# Creates: .git/refs/tags/v1.0-lightweight → commit object ID

Annotated tags are full objects with metadata:


git tag -a v1.0 -m "Release version 1.0"
# Creates a tag object

# Inspect the tag object
git cat-file -p $(git rev-parse v1.0)
# Output:
# object a1b2c3d4e5f6...
# type commit
# tag v1.0
# tagger Test User <test@example.com> 1711886400 +0000
#
# Release version 1.0

Annotated tags contain:

  • object: object ID of the target (usually a commit)
  • type: the type of the object (commit, tree, blob, or tag)
  • tag: the tag name
  • tagger: who created the tag
  • message: the tag message

Production Failure Scenarios

Scenario Symptoms Mitigation
Missing blob “fatal: unable to read tree” Fetch from remote, or restore from backup; blobs are immutable so any copy works
Corrupted tree Directory listing fails Rebuild tree from working tree with git read-tree; verify with git fsck
Broken commit chain git log stops abruptly Use git replace to graft history, or rebase onto valid ancestor
Tag pointing to wrong type Unexpected behavior on tag checkout Verify with git cat-file -t; recreate annotated tag if needed
Object store corruption Multiple “bad object” errors Run git fsck --full; clone fresh from remote; restore from backup

Trade-off Analysis

Aspect Advantage Disadvantage
Content-addressable storage Deduplication and integrity checks SHA-1 is the default; SHA-256 repositories have interoperability limits
Logical snapshots via trees Simple commit model; unchanged objects can be reused Packs may delta-compress similar objects on disk
Immutable objects Safe concurrent access, easy replication No in-place updates; every change creates new objects
No filenames in blobs Blobs can be shared across trees Must traverse tree to find which file a blob belongs to

Implementation Snippets


# Create a blob and store it
echo "content" | git hash-object -w --stdin

# Read a blob's content
git cat-file -p <object-id>

# Get object type
git cat-file -t <object-id>

# Get object size
git cat-file -s <object-id>

# Create a tree from index
git write-tree

# Read a tree into index
git read-tree <tree-object-id>

# Create a commit object
git commit-tree <tree-object-id> -p <parent-object-id> -m "message"

# Create an annotated tag object
git mktag << EOF
object <commit-object-id>
type commit
tag v1.0
tagger Name <email> date
EOF

# List all objects in the repository
git rev-list --objects --all

# Find all unreachable objects
git fsck --unreachable

Observability Checklist

  • Monitor: Object count growth with git count-objects -v
  • Verify: Run git fsck periodically to detect corruption
  • Track: Ratio of loose to packed objects (should favor packed)
  • Alert: Unexpected object count spikes (may indicate accidental large file commits)
  • Audit: Tag signatures for release integrity verification

Security & Compliance Considerations

  • Object hashes provide integrity verification — tampering changes the hash
  • SHA-1 remains the default; Git also supports SHA-256 repositories, but the formats do not interoperate directly. Check the current client and server compatibility before using SHA-256.
  • Signed tags (GPG/SSH) provide non-repudiation for releases
  • Objects are not encrypted — sensitive data in blobs is readable by anyone with repo access
  • See Git Secrets Management for preventing secret commits

Common Pitfalls / Anti-Patterns

  • Assuming blob size equals file size — blobs include a header; use git cat-file -s for actual size
  • Confusing lightweight and annotated tags — lightweight tags are just refs, not objects
  • Modifying objects directly — objects are immutable; use Git commands to create new ones
  • Ignoring unreachable objects — they consume space until git gc prunes them
  • Storing large binary files as blobs — use Git LFS instead

Quick Recap Checklist

  • Blobs store file content only — no filenames or metadata
  • Trees map filenames to blob/tree object IDs — represent directories
  • Commits point to a tree, parent(s), and record authorship
  • Annotated tags are full objects; lightweight tags are just refs
  • Object IDs use the repository’s configured hash format
  • Objects are immutable and zlib-compressed
  • The object graph forms a directed acyclic graph (DAG)
  • Use git cat-file to inspect any object by type, size, or content

Object Relationship Diagram (Clean)


graph TD
    REPO["Repository"] -->|contains| TAGS["Annotated Tags"]
    TAGS -->|points to| COMMITS["Commits"]
    COMMITS -->|tree ref| TREES["Trees"]
    COMMITS -->|parent ref| PARENTS["Parent Commits"]
    TREES -->|entries| SUBTREES["Subdirectory Trees"]
    TREES -->|entries| BLOBS["Blobs (file content)"]
    SUBTREES -->|entries| MORE_BLOBS["More Blobs"]

    BLOBS -->|content only| FILES["Raw File Bytes"]
    MORE_BLOBS -->|content only| FILES

Production Failure: Corrupted Object Database

Scenario: Missing blob causing checkout failure


# Symptoms
$ git checkout main
error: unable to read sha1 file (src/config.py)
fatal: unable to checkout working tree

$ git fsck --full
error: abc123def456...: object missing
error: 789ghi...: object corrupt

# Root cause: Disk corruption, interrupted gc, or filesystem error
# destroyed blob objects in .git/objects/

# Recovery steps:

# 1. Identify missing objects
git fsck --full 2>&1 | grep "missing"

# 2. Try to fetch missing objects from remote
git fetch origin --refetch

# 3. If remote doesn't have them (local-only commits):
#    Check reflog for last known good state
git reflog
git checkout HEAD@{1}  # Try previous HEAD

# 4. As last resort, clone fresh and cherry-pick
cd ..
git clone https://github.com/user/repo.git repo-clean
cd repo-clean
git --git-dir=../repo/.git cherry-pick <object-id>

# 5. Prevent future corruption:
#    - Use reliable storage (SSD > HDD for .git/)
#    - Run git fsck periodically
#    - Keep remote backups
git push origin --mirror  # Full backup

Trade-offs: Annotated vs Lightweight Tags

Aspect Annotated Tags Lightweight Tags
Object type Full tag object in .git/objects/ Simple ref file in .git/refs/tags/
Metadata Tagger name, email, date, message None
GPG signing Supported (git tag -s) Not supported
Storage ~200 bytes per tag 40-character ID in SHA-1 format or 64-character ID in SHA-256 format
Immutability Immutable once created Can be moved with git tag -f
Use case Releases, public milestones Private bookmarks, temporary markers
git describe Works correctly May not show tag message
Platform display Shows message on GitHub/GitLab Shows as simple pointer

Recommendation: Use annotated tags for anything public or release-related. Lightweight tags are fine for personal, temporary markers.

Implementation: Creating and Inspecting Each Object Type Manually


# === 1. BLOB ===
# Create blob from string
BLOB_SHA=$(echo "file content" | git hash-object -w --stdin)
echo "Blob object ID: $BLOB_SHA"

# Create blob from file
git hash-object -w myfile.txt

# Inspect
git cat-file -t $BLOB_SHA   # blob
git cat-file -s $BLOB_SHA   # size in bytes
git cat-file -p $BLOB_SHA   # content

# === 2. TREE ===
# Build index, then create tree
echo "100644 blob $BLOB_SHA test.txt" | git mktree
# Output: TREE_SHA

# Or from current index
TREE_SHA=$(git write-tree)

# Inspect
git cat-file -t $TREE_SHA   # tree
git cat-file -p $TREE_SHA   # entries (mode, type, object ID, name)

# === 3. COMMIT ===
# Create commit (requires env vars for author)
export GIT_AUTHOR_NAME="Test"
export GIT_AUTHOR_EMAIL="test@example.com"
export GIT_COMMITTER_NAME="Test"
export GIT_COMMITTER_EMAIL="test@example.com"

COMMIT_SHA=$(echo "Initial commit" | git commit-tree $TREE_SHA)

# Inspect
git cat-file -t $COMMIT_SHA   # commit
git cat-file -p $COMMIT_SHA   # tree, author, committer, message

# === 4. ANNOTATED TAG ===
# Create tag object
git tag -a v1.0 -m "Release 1.0" $COMMIT_SHA

# Get tag object ID (not the commit it points to)
TAG_SHA=$(git rev-parse v1.0^{tag})

# Inspect
git cat-file -t $TAG_SHA   # tag
git cat-file -p $TAG_SHA   # object, type, tag, tagger, message

# === Verify the chain ===
echo "Tag -> Commit -> Tree -> Blob"
git cat-file -p $TAG_SHA | grep "^object"
git cat-file -p $COMMIT_SHA | grep "^tree"
git cat-file -p $TREE_SHA | grep "blob"

Pack Files and Object Compression

Loose objects (individual files in .git/objects/) are eventually packed into pack files for efficiency:


# Let Git run its standard object maintenance
git gc

# List packed objects
git verify-pack -v .git/objects/pack/*.idx

# See pack file statistics
git count-objects -v

Pack file structure:


graph TD
    LOOSE["Loose Objects\n(individual files)"] -->|git gc triggers| PACKING["Packing Process"]
    PACKING -->|delta compression| PACK["Pack File\n(.pack)"]
    PACK -->|index for fast lookup| IDX["Pack Index\n(.idx)"]
    PACK -->|reduced storage| STORED["Smaller on disk\n(~10-20% of loose)"]

How packing works:

  1. Git finds related objects (similar content, same repository)
  2. Stores one “base” object plus deltas (differences) for others
  3. Creates .idx file for O(log n) object-ID lookups
  4. Result: 10-20x storage reduction for text files

Why pack files matter:

  • Clone and fetch operations transfer pack files, not loose objects
  • Deduplication happens across all branches and history
  • git clone --reference uses pack files for storage optimization

The Index (Staging Area)

The index (.git/index) is a binary file that maps tracked files to blob object IDs — it’s the staging area between working tree and repository.


# View the index
git ls-files --stage

# Sample output:
# 100644 abc123... 0    file1.txt
# 100644 def456... 0    file2.sh
# 040000 789abc... 0    subdir/

# Inspect index structure
git cat-file -p 2b3c4d...  # Use write-tree output to see tree structure

Index entries contain:

  • Mode: File permissions (100644, 100755, etc.)
  • Object ID: Identifier Git derives for the blob from its type and content
  • Stage: 0 for normal entries, 1-3 for merge conflicts
  • Name: Relative path from repository root

Index vs Trees:

Aspect Index Tree
Location .git/index .git/objects/ (object-ID-named)
Mutability Updates on every git add Immutable once created
Scope Single branch (current) Any commit in history
Purpose Staging area, merge conflict resolution Snapshot of directory at commit

Index workflow:


flowchart TD
    WORKING["Working Tree\n(modified files)"] -->|git add| INDEX["Index\n(staged content)"]
    INDEX -->|git commit| TREE["Tree Object\n(snapshot)"]
    TREE -->|commit| REPO["Repository\n(permanent)"]
    WORKING -.->|git diff| INDEX

Interview Questions

1. Why don't Git blobs store filenames?

Blobs store only file content to enable deduplication. If two files in different directories have identical content, they share the same blob. Filenames are stored in tree objects, which map names to blob object IDs. This separation means renaming a file doesn't create a new blob — only a new tree.

2. How does Git detect if an object has been corrupted?

Git computes an object ID from the object's type, size, and content using the repository's hash format. When Git reads an object, it checks that the computed ID matches the stored name. A mismatch indicates corruption. SHA-1 repositories use 40 hexadecimal characters; SHA-256 repositories use 64.

3. What's the difference between git hash-object and git hash-object -w?

Without -w, git hash-object computes and prints an object ID without storing the object. With -w, it also writes the object to the repository's object database. The output format follows the repository's hash algorithm.

4. Can a commit have zero parents? When?

Yes — the initial commit of any repository has zero parents. Additionally, commits created with git commit-tree without the -p flag, or orphan branches created with git checkout --orphan, produce commits with no parent. This creates a new root in the commit DAG.

5. How do annotated tags differ from lightweight tags internally?

An annotated tag creates a full tag object in .git/objects/ with metadata (tagger, date, message, GPG signature). A lightweight tag is just a file in .git/refs/tags/ containing a commit object ID — no tag object is created. Annotated tags are preferred for releases because they're immutable and verifiable.

6. What happens to blobs when a file is deleted in Git?

Blobs are never automatically deleted — they are immutable and retained indefinitely. When you delete a file and commit, Git creates a new tree that no longer references the blob's object ID, but the blob itself remains in `.git/objects/`. This enables recovery via reflog or dangling blob recovery. Blobs are only pruned by `git gc` when they become unreachable (no refs point to them) and are older than the expiration window.

7. How does `git fsck` detect object corruption?

git fsck checks object IDs against object content and verifies that referenced objects exist. It traverses objects reachable from refs and can also report unreachable objects. Use git fsck --full for a more complete integrity check; pack indexes also contain CRC checksums for packed data.

8. Which hash formats can Git use for object IDs?

SHA-1 is Git's default object format, and Git can create SHA-256 repositories when enabled. The formats use 40- and 64-character hexadecimal object IDs, respectively, and the official git-init documentation warns that SHA-1 and SHA-256 repositories do not interoperate directly. Choose a format only after checking the versions and hosting used by every contributor and automation client.

9. Can you have a commit with multiple parent commits? When?

Yes — merge commits have two or more parent commits. The first parent is typically the branch you were on when merging; additional parents are the commits from merged branches. This forms a directed acyclic graph (DAG) rather than a simple chain. Octopus merges can have even more parents (e.g., `git merge branch1 branch2 branch3`).

10. What is the difference between git cat-file -p, -t, and -s?

-p pretty-prints the object's content in human-readable format. -t shows only the object type (blob, tree, commit, tag). -s shows only the size in bytes. These correspond to the three parts of the raw object header: type, size, and content.

11. How does Git store directory structures in tree objects?

Directories are represented as tree objects themselves. Each tree entry has a mode (040000 for directories), an object ID pointing to either a blob (file) or another tree (subdirectory), and the filename. When you `git add` a new file, Git creates a blob, updates the tree, and recursively updates parent trees — all as separate immutable objects.

12. What happens when you rename a file in Git?

Git's rename detection works via content similarity (optional, enabled with `-M` flag in `git diff`). Internally: a rename creates a new tree entry pointing to the existing blob (deduplication means the blob stays the same). Git compares old and new trees to infer renames. No blob is created or destroyed — only the tree structure changes.

13. How do you recover a dangling (unreachable) blob?

Dangling blobs are not referenced by any commit or ref but still exist in the object store. To find them: git fsck --unreachable --no-reflogs. To view content: git cat-file -p <object-id>. To recover: create a blob reference via `git hash-object -w <file>` if you have the content. Dangling blobs are often temporary from operations like `git rebase` or `git reset --soft`.

14. What is the maximum size Git can handle for a single object?

Git has no hard limit on object size — theoretically up to 2^63 bytes. In practice, Git becomes inefficient with objects larger than ~2GB (due to memory for delta compression). For large files, use Git LFS which stores pointer files in the repository and the actual content on LFS servers. Before Git LFS existed, large binary files caused repository bloat.

15. Why might two identical files have different blob object IDs?

Two files with identical blob content in the same repository format produce the same blob object ID, regardless of their path. If IDs differ, compare the exact bytes being hashed; line endings or other content differences can change the blob. File mode and pathname are stored in the tree, not in the blob.

16. What is the .git/objects/pack directory for?

Pack files store multiple objects compressed together using delta encoding. Git groups similar objects (e.g., successive versions of a file) and stores only the differences plus a base object. This reduces storage by 10-20x for text files. The `.idx` file provides O(log n) object-ID lookups. Running git gc converts loose objects to pack files; git clone primarily transfers pack files.

17. Can you modify a commit's tree object ID? What happens?

Commits are immutable — you cannot modify any field including the tree object ID. To change what's in a commit, you must create a new commit with a different object ID. This is what operations like `git commit --amend`, `git rebase`, and `git cherry-pick` do internally. The old commit remains (becomes dangling) until garbage collected.

18. How does Git handle file permission changes in trees?

Tree entries store file mode as an octal number: 100644 (regular file), 100755 (executable), 040000 (subdirectory), 120000 (symlink). When permissions change, Git creates a new tree entry with the updated mode but same blob object ID (if content unchanged). This is why `git diff` can show permission-only changes.

19. What is the relationship between refs, objects, and the HEAD pointer?

Refs (branches, tags) are pointers to commit object IDs stored in `.git/refs/`. HEAD is a special ref pointing to the current commit. Objects (blobs, trees, commits, tags) are stored in `.git/objects/`. When you commit, Git: (1) creates a tree from the index, (2) creates a commit pointing to that tree and the current HEAD, (3) updates HEAD and the current branch ref to the new commit.

20. Why does Git store content by hash and what problems does content-addressable storage solve?

Content-addressable storage names objects by their object IDs. Identical blob content can reuse one blob object across paths, and unchanged trees can be reused across commits. Git can also delta-compress objects in pack files. Changing bytes creates a different object ID; the specific hash algorithm is selected by the repository's format.

Further Reading

  • Git Objects - This article
  • Git LFS - Large file handling
  • Official Git documentation: git cat-file, git hash-object, git write-tree

Conclusion

Git’s object model — blobs for content, trees for structure, commits for snapshots, tags for anchors — is elegant in its simplicity. Every Git operation is a dance between these four object types. Master them and you master Git.

Category

Related Posts

Git References and HEAD

Understand Git refs, branches, tags, HEAD, detached HEAD, and object IDs across SHA-1 and SHA-256 formats for safer history recovery.

#git #version-control #refs

Semantic Versioning and Git Tags: SemVer, Tag Types, and Management Strategies

Master semantic versioning (SemVer 2.0.0), lightweight vs annotated git tags, tag management strategies, and automated versioning workflows for production software releases.

#git #version-control #semver

Centralized vs Distributed VCS: Team Trade-offs

Compare centralized and distributed version control by offline work, repository size, access control, branching, review, and migration effort.

#git #version-control #svn